I am trying to write a script that starts with the most inner XML element and loops up the XML node until it gets to a specific node:
For example:
<bookstore>
<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="children">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="web">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
Let's say my pointer is on the element:
<year>2003</year>
and I want to loop trough the XML object until I get to the element ( note , that I don't know the names of any other elements except the root one, and don't know the size of the tree, this one is just an abstract example). With each iteration I want my pointer to be stored in an array as an element name and then move to the parent node, the iteration should continue until it gets to the root element (included).
I tried several while loops and used the xmlElement.ParentNode. My issue always ends up at not knowing how to move to the parent element of the current pointer because the start of the iteration always points to the original element.
This is my script:
[xml]$File = Get-Content -Path $Path
# Write-Host($File.ManuScript.properties)
$nodes = (Select-Xml -Xml $File -XPath ("//*[starts-with(@value,'Carrier_')]"))
# write-host($nodes.GetType())
#
foreach ($node in $nodes) {
[string] $nodeName = $node.Node.get_name()
# Write-Host("*********")
# Write-Host($nodeName)
# Write-Host("++++++++++")
$XpathElmArr = [System.Collections.ArrayList]@()
$XpathElmArr.Insert(0,$nodeName);
while ($node.Node.get_name() -ne "topic"){
$tempNode = $node.ParentNode
$XpathElmArr.Insert(0,$tempNode.get_name());
$tempNode = $tempNode.ParentNode
Write-Host($node.Node.get_name())
}
Write-Host($XpathElmArr)
}
Appreciate any help.