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() } } }
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.
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.
childNodes returns nodes: Element nodes, text nodes, and comment nodes. Whitespace between elements are also text nodes.
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.
You can use SelectNodes(xpath)
method instead of ChildNodes
property:
foreach(XmlNode child in node.SelectNodes("property")) { doSomethingElse() }
Demo.
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(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With