Get item depth

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 elements using linq for xml

test level = 1 test level 2 = 2 test level 3 = 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 for xml might offer something better.

+4
source share
2 answers

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

myXElement.AncestorsAndSelf().Count()

must indicate the depth of any element.

+5
source

When you have the root element, you can find the depth of each 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()}); 
0
source

Source: https://habr.com/ru/post/1300467/


All Articles