Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating through all nodes in XML file

Tags:

c#

xml

I want to iterate through all nodes in an XML file and print their names. What is the best way to do this? I am using .NET 2.0.

like image 831
Night Walker Avatar asked May 26 '10 17:05

Night Walker


People also ask

What is the difference between XDocument and XmlDocument?

XDocument is from the LINQ to XML API, and XmlDocument is the standard DOM-style API for XML. If you know DOM well, and don't want to learn LINQ to XML, go with XmlDocument . If you're new to both, check out this page that compares the two, and pick which one you like the looks of better.

How do I find the number of nodes in XML?

Count the XML elements (XPath) newXPath(); NodeList nodes = (NodeList) xpath. evaluate("//staff", doc, XPathConstants. NODESET); int count = nodes. getLength();

What are nodes in XML?

Everything in an XML document is a node. For example, the entire document is the document node, and every element is an element node. The topmost node of a tree. In the case of XML documents, it is always the document node, and not the top-most element.


2 Answers

You can use XmlDocument. Also some XPath can be useful.

Just a simple example

XmlDocument doc = new XmlDocument(); doc.Load("sample.xml"); XmlElement root = doc.DocumentElement; XmlNodeList nodes = root.SelectNodes("some_node"); // You can also use XPath here foreach (XmlNode node in nodes) {    // use node variable here for your beeds } 
like image 193
Incognito Avatar answered Sep 17 '22 14:09

Incognito


I think the fastest and simplest way would be to use an XmlReader, this will not require any recursion and minimal memory foot print.

Here is a simple example, for compactness I just used a simple string of course you can use a stream from a file etc.

  string xml = @"     <parent>       <child>         <nested />       </child>       <child>         <other>         </other>       </child>     </parent>     ";    XmlReader rdr = XmlReader.Create(new System.IO.StringReader(xml));   while (rdr.Read())   {     if (rdr.NodeType == XmlNodeType.Element)     {       Console.WriteLine(rdr.LocalName);     }   } 

The result of the above will be

parent child nested child other 

A list of all the elements in the XML document.

like image 42
Chris Taylor Avatar answered Sep 20 '22 14:09

Chris Taylor