定义元素距离 XML 的根有多远

Define how far element is from the root of 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 是根,所以距离 == 0

item 直接在 root 下,所以距离为 1

名称低于 2 级,因此距离为 2

如何在 C# 中为 XElement 动态定义这样的距离?

您应该可以使用父级 属性,计算步骤直到到达根:

public int GetElmtDepth(XDocument doc, XElement elmt)
{
    var (depth, target) = (0, elmt);

    while (target != doc.Root)
        (depth, target) = (depth + 1, target.Parent);

    return depth;
}

您可以简化 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}");
    }
}

输出:

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

未来的读者可能希望看到计算元素深度的纯 XPath 解决方案:

  1. Select 使用任何方法的目标元素,例如 id://*[@id="1001"].
  2. Select 所有祖先://*[@id="1001"]/ancestor::*
  3. 数一数那些祖先:count(//*[@id="1001"]/ancestor::*).

这 returns 3 对于给定的 XML,符合预期。