解析缺少预期子节点的XML

时间:2017-10-25 14:26:52

标签: c# xml linq linq-to-xml

我使用LINQ to XML解析XML片段,我发现我选择的节点之一缺少我期待的子节点。

示例XML

<CustomerList>
  <Customer>
    <LastName>Smith</LastName>
    <FirstName>Todd</FirstName>
  </Customer>
  <Customer>
    <LastName>Jones</LastName>
    <FirstName>Fred</FirstName>
  </Customer>
  <Customer>Tom Jones</Customer> <!-- Missing child nodes -->
</CustomerList>

当我尝试提取LastNameFirstName值时,我收到错误Object reference not set to an instance of an object.

使用LINQ解析XML

XDocument xml = XDocument.Parse(xmlResponse);
List<CustomerModel> nodeList = xml.Descendants("CustomerList")
                          .Descendants("Customer")
                          .Select(x => new CustomerModel
                          {
                            LastName = x.Element("LastName").Value,
                            FirstName = x.Element("FirstName").Value,
                          }).ToList<CustomerModel>();

如果<Customer>个节点没有<LastName><FirstName>个节点,我如何跳过它们或者更好但是甚至不首先选择它们?

1 个答案:

答案 0 :(得分:1)

我的建议是:

XDocument xml = XDocument.Parse(xmlResponse);
List<CustomerModel> nodeList = xml.Descendants("CustomerList")
                      .Descendants("Customer")
                      .Where(x => x.Element("LastName") != null && x.Element("FirstName") != null)
                      .Select(x => new CustomerModel
                      {
                        LastName = x.Element("LastName").Value,
                        FirstName = x.Element("FirstName").Value,
                      }).ToList<CustomerModel>();