按名称选择子节点的子集

时间:2021-02-14 23:48:23

Given this xml doc

鉴于此xml doc

<listOfItem>
  <Item id="1"> 
    <attribute1 type="foo"/>
    <attribute2 type="bar"/>
    <property type="x"/>
    <property type="y"/>
    <attribute3 type="z"/>
  </Item>
  <Item>
   //... same child nodes
  </Item>
 //.... other Items
</listOfItems>

Given this xml document, I would like to select, for each "Item" node, just the "property" child nodes. How can I do it in c# directly? With "directly" I mean without selecting all the child nodes of Item and then check one by one. So far:

给定这个xml文档,我想为每个“Item”节点选择“property”子节点。我怎么能直接在c#中做到这一点?使用“直接”我的意思是不选择Item的所有子节点,然后逐个检查。至今:

XmlNodeList nodes = xmldoc.GetElementsByTagName("Item");
foreach(XmlNode node in nodes)
{
   doSomething()
   foreach(XmlNode child in node.ChildNodes)
   {
     if(child.Name == "property")
     {
        doSomethingElse()
     }
   }
}

2 个解决方案

#1


10  

You can use SelectNodes(xpath) method instead of ChildNodes property:

您可以使用SelectNodes(xpath)方法而不是ChildNodes属性:

foreach(XmlNode child in node.SelectNodes("property"))
{
    doSomethingElse()
}

Demo.

演示。

#2


2  

Try using LINQ to XML instead of XML DOM as it's much simpler syntax for what you want to do.

尝试使用LINQ to XML而不是XML DOM,因为它是您想要做的更简单的语法。

XDocument doc = XDocument.Load(filename);
foreach (var itemElement in doc.Element("listOfItems").Elements("Item"))
{
   var properties = itemElement.Elements("property").ToList();
}

#1


10  

You can use SelectNodes(xpath) method instead of ChildNodes property:

您可以使用SelectNodes(xpath)方法而不是ChildNodes属性:

foreach(XmlNode child in node.SelectNodes("property"))
{
    doSomethingElse()
}

Demo.

演示。

#2


2  

Try using LINQ to XML instead of XML DOM as it's much simpler syntax for what you want to do.

尝试使用LINQ to XML而不是XML DOM,因为它是您想要做的更简单的语法。

XDocument doc = XDocument.Load(filename);
foreach (var itemElement in doc.Element("listOfItems").Elements("Item"))
{
   var properties = itemElement.Elements("property").ToList();
}