Get the depth of an Item

I have xml like this:

<A><B>test</B><B><B>test2</B></B><B><B><B>test2</B></B></B></A>

How can I get the level of each of these items using linq to xml

level of test=1 level of test2=2 level of test3=3

I have no idea how many nodes there will be or how many levels there will be. I can write this as a recursive function but I thought linq to xml might have something better to offer.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Assuming you’ve loaded your XML as an XDocument or XElement object,

myXElement.AncestorsAndSelf().Count()

should give you the depth of any given element.

Method 2

When you have a root element you can find depth of every text node as follows:

var depths =
  root.
    DescendantNodesAndSelf().
    Where(e => e.NodeType == XmlNodeType.Text).
    Select(n => new { Text = n.ToString(), Depth = n.Parent.Ancestors().Count()});


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x