[英]Define how far element is from the root of XML
Consider an XML:考虑一个 XML:
<items>
<item id="0001" type="donut">
<name>Cake</name>
<ppu>0.55</ppu>
<batters>
<batter id="1001">Regular</batter>
<batter id="1002">Chocolate</batter>
<batter id="1003">Blueberry</batter>
</batters>
<topping id="5001">None</topping>
<topping id="5002">Glazed</topping>
<topping id="5005">Sugar</topping>
<topping id="5006">Sprinkles</topping>
<topping id="5003">Chocolate</topping>
<topping id="5004">Maple</topping>
</item>
</items>
items is the root, so distance == 0 items 是根,所以距离 == 0
item is directly under root, so the distance would be 1 item 直接在根目录下,因此距离为 1
name is 2 levels under so the distance would be 2名称在 2 级以下,因此距离为 2
How do I define such distance dynamically for an XElement in C#?如何为 C# 中的 XElement 动态定义这样的距离?
You should be able to use the Parent property, counting steps until you get to the root:您应该能够使用 Parent 属性,计算步骤直到您到达根:
public int GetElmtDepth(XDocument doc, XElement elmt)
{
var (depth, target) = (0, elmt);
while (target != doc.Root)
(depth, target) = (depth + 1, target.Parent);
return depth;
}
You could simplify the System.Xml.XmlTextReader.Depth
example from MSDN to display the node elements and their respective depths:您可以简化MSDN中的System.Xml.XmlTextReader.Depth
示例以显示节点元素及其各自的深度:
// XML file to be parsed.
string xmlFilePath = @"C:\test.xml";
// Create the reader.
using XmlTextReader reader = new XmlTextReader(xmlFilePath);
// Parse the XML and display each node.
while (reader.Read())
{
// If node type is an element
// Display element name and depth
if (reader.NodeType == XmlNodeType.Element)
{
Console.WriteLine($"Element = {reader.Name}, Depth = {reader.Depth}");
}
}
Output: Output:
Element = items, Depth = 0
Element = item, Depth = 1
Element = name, Depth = 2
Element = ppu, Depth = 2
Element = batters, Depth = 2
Element = batter, Depth = 3
Element = batter, Depth = 3
Element = batter, Depth = 3
Element = topping, Depth = 2
Element = topping, Depth = 2
Element = topping, Depth = 2
Element = topping, Depth = 2
Element = topping, Depth = 2
Element = topping, Depth = 2
Future readers may like to see a pure XPath solution to calculating element depth:未来的读者可能希望看到计算元素深度的纯 XPath 解决方案:
//*[@id="1001"]
. Select 使用任何方法的目标元素,比如通过 id: //*[@id="1001"]
。//*[@id="1001"]/ancestor::*
Select 所有祖先: //*[@id="1001"]/ancestor::*
count(//*[@id="1001"]/ancestor::*)
.计算那些祖先: count(//*[@id="1001"]/ancestor::*)
。 This returns 3
for the given XML, as expected.正如预期的那样,这将为给定的 XML 返回3
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.