Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 773
zachary Avatar asked Feb 05 '10 20:02

zachary


1 Answers

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

myXElement.AncestorsAndSelf().Count()

should give you the depth of any given element.

like image 52
womp Avatar answered Nov 10 '22 00:11

womp