Get the depth of an Item

情到浓时终转凉″ 提交于 2020-01-29 13:29:09

问题


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


来源:https://stackoverflow.com/questions/2210162/get-the-depth-of-an-item

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!