If you do not require functionality specific to the XmlDocument class, it is easier to use the XDocument from the System.Xml.Linq namespace. This will provide a more compact code.
For output to the console in the form that you indicated there are three ways.
1. Recursively traversing an XML tree
It is implemented quite simply:
static void Main(string[] args) { XElement doc = XElement.Load(@"H:\test.xml"); PrintElementV1(doc); Console.ReadKey(); } static void PrintElementV1(XElement elem) { if (elem.Elements().Count() > 0) { Console.WriteLine(elem.Name); foreach (XElement e in elem.Elements()) { PrintElementV1(e); } } else { Console.WriteLine("{0}: {1}", elem.Name, elem.Value); } }
But to insert into this water the electoral numbering of specific elements without “crutches” will not work. The “crutch” for numbering may look like this:
static void PrintElementV1(XElement elem, int num) { if (elem.Elements().Count() > 0) { Console.WriteLine("{0}. {1}", num, elem.Name); int i = 1; foreach (XElement e in elem.Elements()) { PrintElementV1(e, i++); } } else { Console.WriteLine("{0}: {1}", elem.Name, elem.Value); } }
In this case, all elements except those that do not contain other elements will be numbered.
2. Fixed traversal of the XML tree
From the point of view of the tree, the recursion is preserved, such is the structure of the tree, but if this structure is fixed and known , then you can do without recursive calling methods and use a chain of calls in a loop. I will show by example:
static void Main(string[] args) { XElement doc = XElement.Load(@"H:\test.xml"); Console.WriteLine(doc.Name); PrintCDList(doc); Console.ReadKey(); } static void PrintCDList(XElement elem) { int i = 1; foreach (XElement e in elem.Elements()) { Console.WriteLine("{0}. {1}", i++, e.Name); PrintContent(e); } } static void PrintContent(XElement elem) { foreach (XElement e in elem.Elements()) { Console.WriteLine("{0}: {1}", e.Name, e.Value); } }
As you can see, there is no recursion, but if the XML structure differs from the one in the code, “everything will turn into a pumpkin” and will give incorrect results.
3. Manual parsing
You can do all the work with your hands by getting the XML source text as text. To do this, you can use any way you know how to get text from a file.
Next, we apply all sorts of regular expressions or other methods of transforming a string to the source XML string to obtain a string or an array of strings of the desired type and print the result.
I will not give the code of this method, because there are a lot of options for such a solution, and there are many other views on how to do it correctly. In addition, I strongly doubt that this option will be much more productive than the previous two, rather the opposite.
Choose which option suits you best =)
PS: If it is important to use XmlDocument , write in the comments, I will add the corresponding example.