2015-06-30 144 views
0

如何獲得第一個狀態<StatusType>元素<Code>是D.此LINQ工作,但重新說明x.Element("StatusType")可能的nullreferenceexpection。嵌套的XML元素拋出異常

var aaa = track.Descendants("Status") 
    .SingleOrDefault(x => x.Element("StatusType") != null && 
          x.Element("StatusType").Element("Code").Value == "D"); 

XML: -

<Activity> 
<ActivityLocation> 
<Address> 
<City>WILSLLE</City> 
<StateProvinceCode>oR</StateProvinceCode> 
<PostalCode>978880</PostalCode> 
<CountryCode>US</CountryCode> 
</Address> 
<Code>M7</Code> 
<Description>RECEIVER</Description> 
<SignedForByName>abc</SignedForByName> 
</ActivityLocation> 
<Status> 
<StatusType> 
<Code>D</Code> 
<Description>DELIVERED</Description> 
</StatusType> 
<StatusCode> 
<Code>KB</Code> 
</StatusCode> 
</Status> 
<Date>20150504</Date> 
<Time>085100</Time> 
</Activity> 
<Activity> 
<ActivityLocation> 
<Address> 
<City>TUALATIN</City> 
<StateProvinceCode>OR</StateProvinceCode> 
<CountryCode>US</CountryCode> 
</Address> 
</ActivityLocation> 
<Status> 
<StatusType> 
<Description>OUT FOR DELIVERY</Description> 
</StatusType> 
<StatusCode> 
<Code>DS</Code> 
</StatusCode> 
</Status> 
<Date>20150504</Date> 
<Time>045600</Time> 
</Activity> 

回答

0

與您的代碼的問題是,一些StatusType節點不包含Code標籤本身因此將返回null,.Value拋出一個空引用異常。最好是按如下方式輸入您的值,因爲顯式轉換運算符比訪問Value屬性安全得多,因爲它首先會檢查null

var result = xdoc.Descendants("Status") 
       .SingleOrDefault(x => x.Element("StatusType") != null && 
          (string)x.Element("StatusType").Element("Code") == "D"); 

另外,如果你很確定你的過濾器的查詢將返回僅1節點僅然後用SingleOrDefault否則FirstOrDefault是更好的選擇。