代码之家  ›  专栏  ›  技术社区  ›  One Developer

XML文档深度?

  •  0
  • One Developer  · 技术社区  · 15 年前

    如何使用powershell/xpath查找xml文件的深度?

    考虑下面的XML:

    <?xml version="1.0" encoding="ISO-8859-1"?>
    <bookstore>
    <book>
      <title>Harry Potter</title>
      <price>25.99</price>
    </book>
    <book>
      <title>Learning XML</title>
      <price>49.95</price>
    </book>
    </bookstore>
    

    上述xml文档的深度为3(书店->图书->标题/价格)。

    2 回复  |  直到 15 年前
        1
  •  1
  •   whenamanlies    11 年前

    不要认为用XPath可以做到这一点,但可以尝试以下方法:

    $xml = [xml]"<?xml version=`"1.0`" encoding=`"ISO-8859-1`"?>
      <bookstore>
        ...
    </bookstore>"
    [System.Xml.XmlElement] $root = $xml.DocumentElement
    $script:depth = 1
    
    function dfs([System.Xml.XmlElement] $node, [int] $level) 
    {
        foreach ($child in $node.ChildNodes)
        {
            if ($child.NodeType -eq 'Element')
            {
                dfs $child ($level+1)
            }
        }
        $script:depth = [Math]::Max($depth, $level)
    }
    
    dfs $root $script:depth
    "Depth: $depth"
    
        2
  •  0
  •   DrDol    15 年前

    差不多

    max(//*[not(*)]/count(ancestor::node()))
    

    应该找到最大深度。但是解析器必须支持XPath 2.0。