如何使用LINQ查询XML文档?

时间:2011-02-06 12:38:58

标签: c# linq linq-to-xml

假设我有以下XML文档:

<response>
   <businessEntity>
      <ABN>
         <identifierValue></identifierValue> 
         <isCurrentIndicator></isCurrentIndicator> 
         <replacedIdentifierValue xsi:nil="true" /> 
         <replacedFrom></replacedFrom> 
      </ABN>
      <entityStatus>
         <entityStatusCode> </entityStatusCode> 
         <effectiveFrom></effectiveFrom> 
         <effectiveTo></effectiveTo> 
      </entityStatus>
      <entityType>
         <entityTypeCode> </entityTypeCode> 
         <entityDescription> </entityDescription> 
      </entityType>
      <goodsAndServicesTax>
          <effectiveFrom></effectiveFrom> 
          <effectiveTo></effectiveTo> 
      </goodsAndServicesTax>
      <legalName>
          <givenName> </givenName> 
          <otherGivenName /> 
          <familyName> </familyName> 
          <effectiveFrom></effectiveFrom> 
          <effectiveTo></effectiveTo> 
      </legalName>
      <mainBusinessPhysicalAddress>
          <stateCode> </stateCode> 
          <postcode></postcode> 
          <effectiveFrom></effectiveFrom> 
          <effectiveTo></effectiveTo> 
      </mainBusinessPhysicalAddress>
   </businessEntity>
</response>

如果我想获取givenName和familyName,我可以这样做:

var businesses = doc.Descendants(ns + "businessEntity")
             .Elements(ns + "legalName")
             .Select(node => new
             {
                 effectiveFrom = node.Element(ns + "effectiveFrom").Value,
                 givenName = node.Element(ns + "givenName").Value,
                 familyName = node.Element(ns + "familyName").Value,
             }).ToList();

然后我可以访问并填充表格,我不知道如何查询整个文档并获取我想要的所有节点,例如ABN和entityType。我是否需要创建一个列表并将每个兄弟代码的一部分复制到legalName?

提前致谢。

1 个答案:

答案 0 :(得分:1)

如果您可以假设每个子元素只出现一次,您可以尝试这种方法:

var businesses = (
    from node in doc.Descendants(ns + "businessEntity")
    let legalName = node.Element(ns + "legalName")
    let abn = node.Element(ns + "ABN")
    // etc...
    select new
    {
        LegalName = new
        {
            EffectiveFrom = (string)legalName.Element(ns + "effectiveFrom"),
            GivenName = (string)legalName.Element(ns + "givenName"),
            FamilyName = (string)legalName.Element(ns + "familyName"),
        },
        Abn = new
        {
            IdentifierValue = (string)abn.Element(ns + "identifierValue"),
            IsCurrentIndicator = (string)abn.Element(ns + "isCurrentIndicator"),
            ReplacedFrom = (string)abn.Element(ns + "replacedFrom"),
        },
        // etc...
    }).ToList();


Console.WriteLine(businesses[0].LegalName.GivenName);
Console.WriteLine(businesses[0].Abn.IsCurrentIndicator);

如果要在解析XML的方法之外使用此数据,您可能还需要考虑使用具体类型而不是匿名类型。