【问题标题】:Nested XML element throwing exception嵌套 XML 元素抛出异常
【发布时间】:2015-06-30 03:20:31
【问题描述】:

如何通过其<StatusType> 元素<Code> 获得第一个状态是 D。此 LINQ 有效,但重新明确指出 x.Element("StatusType") 可能为 nullreferenceexpection。

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>

【问题讨论】:

    标签: c# linq linq-to-xml


    【解决方案1】:

    您的代码的问题是某些 StatusType 节点本身不包含 Code 标记,因此它将返回 null 并且 .Value 会引发 null 引用异常。最好按如下方式对值进行类型转换,因为显式转换运算符比访问 Value 属性更安全,因为它首先检查 null

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

    此外,如果您非常确定您的过滤器查询将只返回 1 个节点,则使用 SingleOrDefault 否则 FirstOrDefault 是更好的选择。

    【讨论】:

      猜你喜欢
      • 2016-01-08
      • 1970-01-01
      • 2017-08-21
      • 2017-11-07
      • 1970-01-01
      • 2018-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多