How to keep track of node levels when we Linq an XML document?

A

Author

I have an xml document that looks *like* so:

<Mammal name="Cat">
<Mammal name="African Tigers" >
<Mammal name="Central African Tiger" />
<Mammal name="Ethiopian Tiger" />
</Mammal>
<Mammal name="Asian Tigers" >
<Mammal name="Indian Tiger" />
<Mammal name="China Tigers" >
<Mammal name="South China Tiger" />
<Mammal name="Northeast China Tiger" />
</Mammal>
</Mammal>
</Mammal>

Well, I understand that this XML can be improved, but I don't have the
option. I have to work on this coarsely designed XML document.

Now, I want to process this XML document and output the list of cats
and keep their hierarchical info like so (I hope the indentation won't
get messed up while you are reading this):

Cat
African Tigers
Central African Tiger
Ethiopian Tiger
Asian Tigers
Indian Tiger
China Tigers
South China Tiger
Northeast China Tiger

I have a way to do this with the traditional XmlDocument API. But, I
cannot figure out how to do this with the Linq XDocument.

I have the following code:

XDocument xd = XDocument.Load(new XmlNodeReader(node));

var cats = from cat in xd.Descendants("Cat") select cat;

foreach (var c in cats)
{
Console.WriteLine(Convert.ToString(c.Attribute("name").Value));
}

This will simply output as this:

Cat
African Tigers
Central African Tiger
Ethiopian Tiger
Asian Tigers
Indian Tiger
China Tigers
South China Tiger
Northeast China Tiger

So, my question is: With Linq to Xml, how do I keep track of the node
level information so that I can add numbers of "\t" (the tab) to the
WriteLine method accordingly?

I hope that I have made my question clear. Thanks a lot.
 
J

Jon Skeet [C# MVP]

So, my question is: With Linq to Xml, how do I keep track of the node
level information so that I can add numbers of "\t" (the tab) to the
WriteLine method accordingly?

I hope that I have made my question clear. Thanks a lot.

Try node.Ancestors().Count()
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top