C# 正在分析缺少预期子节点的XML

C# 正在分析缺少预期子节点的XML,c#,xml,linq,linq-to-xml,C#,Xml,Linq,Linq To Xml,我正在使用LINQ to XML解析一个XML片段,发现我正在选择的一个节点缺少我期望的子节点 示例XML <CustomerList> <Customer> <LastName>Smith</LastName> <FirstName>Todd</FirstName> </Customer> <Customer> <LastName>Jones</

我正在使用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>

节点没有
节点的情况下,我如何跳过它们,或者更好地说,甚至不首先选择它们?

我的建议是:

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>();
xdocumentxml=XDocument.Parse(xmlResponse);
List nodeList=xml.substands(“CustomerList”)
.子公司(“客户”)
其中(x=>x.Element(“LastName”)!=null和&x.Element(“FirstName”)!=null)
.选择(x=>new CustomerModel
{
LastName=x.Element(“LastName”).Value,
FirstName=x.Element(“FirstName”).Value,
}).ToList();

您可以在
之前添加一个
。其中(x=>x.Element(“LastName”)!=null和&x.Element(“FirstName”)!=null)
选择()
@dcg您想说的
。其中(x=>x.Element(“LastName”)!=null)
@RandRandom如果您说得对,我将编辑注释。谢谢。而不是
LastName=x.Element(“LastName”)。Value
使用
LastName=x.Element(“LastName”)?。Value,
这将处理空引用对象,但它将生成带有空
LastName
CustomerModel
,您还可以将查询更改为
xml.substands(“CustomerList”).substands(“Customer”)。其中(x=>x.HasElements)。选择(xxxx)
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>();