PowerShell & XML:如果文本前面有一个点,则无法提取 InnerText 值
PowerShell & XML: cannot extract InnerText value if text is preceded by a dot
示例 XML 文件:
<input>
<filePattern>
<midfix>.bof-fix</midfix>
<format>raw</format>
</filePattern>
</input>
如果我尝试从“格式”元素中提取文本,则以下脚本可以正常工作:
Get-ChildItem -Path "C:\ps_scripts\configs\*" -Recurse |
ForEach-Object {
$xml_file = $_
$curr_dir = $xml_file
$content = [xml](Get-Content $curr_dir)
$nodes = $content.SelectNodes("//input")
foreach ($node in $nodes) {
$format = $node.SelectNodes('filePattern/format').InnerText
$format
}
}
输出为:
raw
但是,如果我修改上面的脚本,将 foreach 循环中的两行替换为:
$midfix = $content.SelectNodes('filePattern/midfix').InnerText
$midfix
然后就完全没有输出了。预期输出:
.bof-fix
这显然是因为文本中的前导点 (.)?
我不知道它是否适用于 PS 5.0,但以这种方式尝试一下,看看它是否有效:
$nodes = $xml.SelectSingleNode("//midfix")
foreach ($node in $nodes) {
$format = $node.InnerText
$format
}
编辑:
反映以下评论:
变化
$nodes = $xml.SelectSingleNode("//midfix")
至
$nodes = $xml.SelectSingleNode("//input//midfix")
示例 XML 文件:
<input>
<filePattern>
<midfix>.bof-fix</midfix>
<format>raw</format>
</filePattern>
</input>
如果我尝试从“格式”元素中提取文本,则以下脚本可以正常工作:
Get-ChildItem -Path "C:\ps_scripts\configs\*" -Recurse |
ForEach-Object {
$xml_file = $_
$curr_dir = $xml_file
$content = [xml](Get-Content $curr_dir)
$nodes = $content.SelectNodes("//input")
foreach ($node in $nodes) {
$format = $node.SelectNodes('filePattern/format').InnerText
$format
}
}
输出为:
raw
但是,如果我修改上面的脚本,将 foreach 循环中的两行替换为:
$midfix = $content.SelectNodes('filePattern/midfix').InnerText
$midfix
然后就完全没有输出了。预期输出:
.bof-fix
这显然是因为文本中的前导点 (.)?
我不知道它是否适用于 PS 5.0,但以这种方式尝试一下,看看它是否有效:
$nodes = $xml.SelectSingleNode("//midfix")
foreach ($node in $nodes) {
$format = $node.InnerText
$format
}
编辑: 反映以下评论: 变化
$nodes = $xml.SelectSingleNode("//midfix")
至
$nodes = $xml.SelectSingleNode("//input//midfix")