我想获取XML路径和属性(如果有的话)。 由于这是一个大型XML,所以我不知道属性在哪里。因此,它必须是动态的。我做了很多尝试,问题是路径看起来像这样,并且我在一个组中有多个步骤。
/root/group/step...
以下是XML的示例:
<root>
<group name="Name" attribute="some text" id="123123">
<step name="Name" ...>Some more text
</step>
<step name="Name"...>2. Step
</step>
</group>
</root>
编辑:
$strXmlPathMain = "myXMl.xml"
$importXMLMain = Import-Clixml -Path $strXmlPathMain
[xml]$xml = $importXMLMain.root
function Get-Root-Structure {
Param(
$xml
)
$array = @()
$nodesWithText = $xml.SelectNodes("//*")
foreach ($node in $nodesWithText) {
#Start with end of path (element-name of the node with text-value)
$path = $node.LocalName
#Get parentnode
$parentnode = $node.ParentNode
#Loop until document-node (parent of root-node)
while ($parentnode.LocalName -ne '#document') {
#If sibling with same LocalName (element-name) exists
if (@($parentnode.ParentNode.ChildNodes | Where-Object {$_.LocalName -eq $parentnode.LocalName}).Count -gt 1) {
#Add text-value to path
#$path = "{0}\$path" -f ($parentnode.'#text').Trim()
}
#Add LocalName (element-name) for parent to path
$path = "$($parentnode.Name)/$path"
$path = $path.Replace("root", "")
#Go to next parent node
$parentnode = $parentnode.ParentNode
}
$array += $path
}
return $array
}
$PathArray = Get-Root-Structure $xml
foreach($i in $PathArray){
$xml | Select-Xml -XPath "$i" | select -ExpandProperty node
}