0

如何使用 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(书店 -> 书 -> 书名/价格)。

4

2 回答 2

1

不要认为你可以用 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"
于 2013-07-18T06:04:58.963 回答
0

就像是

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

应该找到最大深度。但是您的 Parser 必须支持 XPath 2.0。

于 2010-03-30T06:20:32.797 回答