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.
A:
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
}
Incognito
2010-05-26 17:29:33
+1
A:
A recursive algorithm that parses through an XmlDocument
Here is an example - http://stackoverflow.com/questions/825459/recursively-reading-an-xml-document-and-using-regex-to-get-contents
Here is another recursive example - http://www.java2s.com/Tutorial/CSharp/0540__XML/LoopThroughXmlDocumentRecursively.html
Alexander
2010-05-26 17:29:49
+3
A:
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.
Chris Taylor
2010-05-26 17:52:16