如何从属性值中选择并迭代XML xElement节点?

时间:2012-05-01 06:48:48

标签: c# xml linq

我有这样的xml。

<?xml version="1.0" encoding="utf-8" ?>
<Category ID="1" AICategoryName="Schedule K: Income/Loss" Taxonomy="K">
   <Level1 ID="11965" Name="Guaranteed payments" Taxonomy="4">
      <Level2 ID="27058" Name="Gtd Pmts(trade/bus) to Sch. M-1" Taxonomy="1"> 
      </Level2>

      <Level2 ID="27059" Name="Gtd Pmts not to Sch. M-1" Taxonomy="2">      
      </Level2>
   </Level1>

   <Level1 ID="119652" Name="2Guaranteed payments" Taxonomy="4">
      <Level2 ID="227058" Name="2Gtd Pmts(trade/bus) to Sch. M-1" Taxonomy="1"> 
      </Level2>

      <Level2 ID="227059" Name="2Gtd Pmts not to Sch. M-1" Taxonomy="2">      
      </Level2>
   </Level1>
</Category>

我希望通过提供父节点attribite ID来获取父节点下的子节点。

例如,如果我提供Level1和11965,我应该获得所有2级节点及其名称和ID。

我试过这段代码。

XDocument xd = XDocument.Load(xmlPath);

        var xl = from xml2 in xd.Descendants("Level1")
                 where xml2.Parent.Attribute("ID").Value == parentNode.ID
                 select xml2;

但代码没有结果。一旦我得到xl,我怎么能遍历它来获取子节点名称和ID?

2 个答案:

答案 0 :(得分:2)

XDocument xd = XDocument.Load(xmlPath);
var nodes = (from n in xd.Root.Desendants(tagName/*Level1*/) where n.Attribute("Id").Value == "idValue" select n.Elements()).single().select(n=>{return new{
Id = n.attribute("Id").value,
Name = n.attribute("Name").value,
Taxonomy = n.attribute("Taxonomy").value
}});

如果请求的标签名称始终为“Level1”且xml struvvture已修复,您也可以更改上面的代码。

XDocument xd = XDocument.Load(xmlPath);
var nodes = (from n in xd.Root.Elements("Level1") where n.Attribute("Id").Value == "idValue" select n.Elements()).single().select(n=>{return new{
    Id = n.attribute("Id").value,
    Name = n.attribute("Name").value,
    Taxonomy = n.attribute("Taxonomy").value
    }});

答案 1 :(得分:1)

LINQ(假设你总是为提供的id获得单个Level1节点):

XDocument xd = XDocument.Load(xmlPath);
int parentId = 119652;
var nodes = (from level1 in xd.Descendants("Level1")
            where ((int)level1.Attribute("ID")) == parentId
            select level1.Descendants("Level2"))
            .Single()
            .Select(level2 => new { ID = (int)level2.Attribute("ID"), 
                                    Name = level2.Attribute("Name").Value });

迭代

foreach (var level2 in nodes)
    // level2.Name and level2.ID

如果提供的ID可能不存在Level1节点,或者您有多个具有相同ID的Level1节点:

int parentId = 119652;
XDocument xd = XDocument.Load(xmlPath);
var query = xd.Descendants("Level1")
              .Where(level1 => ((int)level1.Attribute("ID")) == parentId)
              .SelectMany(level1 => level1.Descendants("Level2"))
              .Select(level2 => new { ID = (int)level2.Attribute("ID"), 
                                      Name = level2.Attribute("Name").Value });

foreach (var level2 in query)
    // level2.Name and level2.ID