One Developer
One Developer

Reputation: 576

XML Document Depth?

How to find the depth of the xml file using powershell/xpath?

consider the below 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>

depth of the above xml document is 3 (bookstore -> book -> title/price).

Upvotes: 0

Views: 1385

Answers (2)

whenamanlies
whenamanlies

Reputation: 39

Don't think you can do this with XPath but you could try this instead:

$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"

Upvotes: 1

DrDol
DrDol

Reputation: 2240

Something like

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

should find the max depth. But your Parser must support XPath 2.0.

Upvotes: 0

Related Questions