Get the depth of an Item

2019-02-18 01:14发布

问题:

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.

回答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.



回答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()});