Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select a subset of childnodes by name

Tags:

Given this 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:

XmlNodeList nodes = xmldoc.GetElementsByTagName("Item"); foreach(XmlNode node in nodes) {    doSomething()    foreach(XmlNode child in node.ChildNodes)    {      if(child.Name == "property")      {         doSomethingElse()      }    } } 
like image 810
accand Avatar asked May 21 '15 09:05

accand


People also ask

What does childNodes mean?

Child nodes include elements, text and comments. Note: The NodeList being live means that its content is changed each time new children are added or removed. The items in the collection of nodes are objects, not strings. To get data from node objects, use their properties.

What is childNodes in XML?

The childNodes property is a read-only property containing a node list of all children for those elements that can have them. It returns a NodeList for the following valid node types: NODE_ATTRIBUTE.

What does childNodes return?

childNodes returns nodes: Element nodes, text nodes, and comment nodes. Whitespace between elements are also text nodes.

What is XmlNodeList?

XmlNode. SelectNodes - Returns an XmlNodeList containing a collection of nodes matching the XPath query. GetElementsByTagName - Returns an XmlNodeList containing a list of all descendant elements that match the specified name. This method is available in both the XmlDocument and XmlElement classes.


2 Answers

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

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

Demo.

like image 76
Sergey Kalinichenko Avatar answered Oct 25 '22 06:10

Sergey Kalinichenko


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

XDocument doc = XDocument.Load(filename); foreach (var itemElement in doc.Element("listOfItems").Elements("Item")) {    var properties = itemElement.Elements("property").ToList(); } 
like image 39
toadflakz Avatar answered Oct 25 '22 07:10

toadflakz