This came up as a requirement in one of our projects. The objective of this is to put all node names in an excel file. The example I have uses a recursive function to output all node names.
csharp Code:
using System;
using System.Xml;
namespace StripMe
{
class Class1
{
public static int GetNodeTypeCount(XmlNode node, XmlNodeType nodeType)
{
// Recursively loop through the given node and return
// the number of occurences of a specific nodeType.
int i = 0;
if (node.NodeType == nodeType)
i = i + 1;
if (node.HasChildNodes)
foreach (XmlNode cNode in node.ChildNodes)
{
i = i + GetNodeTypeCount(cNode, nodeType);
if (cNode.NodeType == XmlNodeType.Element)
Console.WriteLine(cNode.Name);
}
return i;
}
[STAThread]
static void Main(string[] args)
{
try
{
XmlDocument doc = new XmlDocument();
doc.Load(args[0]);
XmlNodeList nodeList = doc.GetElementsByTagName("*");
Class1.GetNodeTypeCount(doc.DocumentElement, XmlNodeType.Element);
Console.ReadLine();
}
catch (XmlException xmlEx) // Handle the XML Exceptions here.
{
Console.WriteLine("{0}", xmlEx.Message);
}
catch (Exception ex) // Handle the Generic Exceptions here.
{
Console.WriteLine("{0}", ex.Message);
}
}
}
}
Code:
The way to use this is pass the file name that you want to parse as the first parameter.
For e.g -
c:\>TraverseXML Quote.XML