【问题标题】:Define how far element is from the root of XML定义元素与 XML 根的距离
【发布时间】:2020-05-10 13:02:09
【问题描述】:

考虑一个 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 直接在根目录下,所以距离为 1

名称在 2 层以下,因此距离为 2

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

【问题讨论】:

    标签: c# xml linq-to-xml


    【解决方案1】:

    您应该能够使用 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;
    }
    

    【讨论】:

      【解决方案2】:

      您可以从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
      

      【讨论】:

        【解决方案3】:

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

        1. 使用任何方法选择目标元素,例如通过 id://*[@id="1001"]
        2. 选择其所有祖先://*[@id="1001"]/ancestor::*
        3. 算上那些祖先:count(//*[@id="1001"]/ancestor::*)

        这会按预期返回给定 XML 的 3

        【讨论】:

          猜你喜欢
          • 2021-09-23
          • 1970-01-01
          • 1970-01-01
          • 2016-08-13
          • 2016-08-31
          • 1970-01-01
          • 2017-01-10
          • 2014-11-19
          • 1970-01-01
          相关资源
          最近更新 更多