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.
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.
Count the XML elements (XPath) newXPath(); NodeList nodes = (NodeList) xpath. evaluate("//staff", doc, XPathConstants. NODESET); int count = nodes. getLength();
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.
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 }
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.
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