我正在寻找一种遍历基于XML API的响应并以以下格式显示整个XML树的方法:
node\node = VALUE
node\node\node = VALUE
node\node\node2 = VALUE我有一个脚本,它对某些XML输出有效,但对其他XML输出无效:
function Get-XMLTree($xml) {
$nodesWithText = $xml.SelectNodes("//*[text()]")
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.LocalName)\$path"
#Go to next parent node
$parentnode = $parentnode.ParentNode
}
#Output "path = text-value"
"$path = $(($node.'#text').Trim())"
}
}对于某些XML响应,这可以很顺利地工作。对于其他人,我收到类似于以下内容的错误:
InvalidOperation: /script1.ps1:51:17
Line |
51 | $path = "{0}\$path" -f ($parentnode.'#text').Trim()
| You cannot call a method on a null-valued expression.任何帮助我们都将不胜感激
发布于 2020-07-28 07:43:24
修好了!下面是最后一个函数
function Get-XMLTree($xml) {
$nodesWithText = $xml.SelectNodes("//*[text()]")
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
if($parentnode.'#text')
{
$path = "{0}\$path" -f ($parentnode.'#text').Trim()
}
}
#Add LocalName (element-name) for parent to path
$path = "$($parentnode.LocalName)\$path"
#Go to next parent node
$parentnode = $parentnode.ParentNode
}
#Output "path = text-value"
"$path = $(($node.'#text').Trim())"
}
}发布于 2020-07-28 05:48:51
XSLT似乎是从xml格式中提取信息的工具。
This answer给出了如何在powershell中应用xslt的要点。或者,使用许多其他XSLT tools ...中的一个。
正如@mclayton所问的那样--如果你能提供原始的xml,也许有人能给你一个快速的xslt来提取你正在寻找的信息。
https://stackoverflow.com/questions/63119761
复制相似问题