定义元素离XML根的距离

问题描述 投票:0回答:3

考虑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>

项目是根,所以距离== 0

项目直接在根目录下,因此距离为1

名称是2个等级,所以距离将是2

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

c# xml linq-to-xml
3个回答
1
投票

您可以从System.Xml.XmlTextReader.Depth简化MSDN示例以显示节点元素及其各自的深度:
// 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


1
投票

0
投票
[使用任何方法选择目标元素,例如,id://*[@id="1001"]

选择所有祖先://*[@id="1001"]/ancestor::*

    计算那些祖先:count(//*[@id="1001"]/ancestor::*)
© www.soinside.com 2019 - 2024. All rights reserved.