我有以下xml。由於addr在這種情況下是空的,但大部分時間它都有像街道,城市,州這樣的元素。我如何確保它存在。原因現在LINQ查詢會引發錯誤「對象引用未設置爲對象的實例」。使用LINQ選擇是否存在XML元素
<author>
<time value="20120620153233"/>
<assignedAuthor>
<id/>
<addr/>
<telecom value="tel:+1-781-271-3000"/>
<assignedPerson>
<name>Auto Generated</name>
</assignedPerson>
</assignedAuthor>
</author>
tbAuthor autor =
(from c in cdafile.Root.Elements(ns + "author")
select new tbAuthor
{
streetAddressLine = (string)c.Element(ns + "assignedAuthor").Element(ns + "addr").Element(ns + "streetAddressLine").Value,
city = (string)c.Element(ns + "assignedAuthor").Element(ns + "addr").Element(ns + "city").Value,
state = (string)c.Element(ns + "assignedAuthor").Element(ns + "addr").Element(ns + "state").Value,
postalCode = (string)c.Element(ns + "assignedAuthor").Element(ns + "addr").Element(ns + "postalCode").Value,
country = "US"
}).FirstOrDefault();
你怎麼在有ns變量? –