【问题标题】:XML Document Depth?XML 文档深度?
【发布时间】:2010-03-30 06:09:27
【问题描述】:
如何使用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(书店->书->书名/价格)。
【问题讨论】:
标签:
.net
xml
powershell
xpath
powershell-2.0
【解决方案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"
【解决方案2】:
类似
max(//*[not(*)]/count(ancestor::node()))
应该找到最大深度。但是您的 Parser 必须支持 XPath 2.0。