gpt4 book ai didi

xml - PowerShell:如何将InnerText值连接为单个字符串?

转载 作者:行者123 更新时间:2023-12-03 00:55:42 25 4
gpt4 key购买 nike

我在目录中遍历多个XML文件。每个文件具有相同的结构:

<input>
<filePattern>
<marketCode>cbf_d</marketCode>
<format>txt</format>
</filePattern>
</input>
<input>
<filePattern>
<marketCode>lvd_cbf_b</marketCode>
<format>csv</format>
</filePattern>
</input>
<input>
<filePattern>
<marketCode>cbf_a</marketCode>
<format>zip</format>
</filePattern>
</input>
我的目的是循环遍历文件中的每个 input节点,从 InnerTextmarketCode中提取 format值,然后将它们连接为单个字符串:
Get-ChildItem -Path 'C:\test\cbf\*merge*' -Recurse |
ForEach-Object {
$xml_file = $_

$content = [xml](Get-Content $xml_file)
$nodes = $content.SelectNodes('//input')


foreach ($node in $nodes) {
$marketCode = $node.SelectNodes('//input/filePattern/marketCode').InnerText
$format = $node.SelectNodes('//input/filePattern/format').InnerText


}
#Trying to cancatenate InnerText values here:
$marketCode + '_' + $format


}
我得到的输出:
cbf_d
lvd_cbf_b
cbf_a
_
txt
csv
zip
我期望的输出:
cbf_d_txt
lvd_cbf_b_csv
cbf_a_zip
如何正确连接 InnerText的值?

最佳答案

通过使用//input,您可以将基本路径重置为“global”-这意味着忽略上下文节点$node。解决方案是在$node表达式中使用相对路径(相对于SelectNodes)。此外,每个文件只将字符串连接一次,而不是每个<input>元素一次,因此连接操作需要移入循环。

Get-ChildItem -Path 'C:\test\cbf\*merge*' -Recurse |
ForEach-Object {
$xml_file = $_

$content = [xml](Get-Content $xml_file)
$nodes = $content.SelectNodes('//input')


foreach ($node in $nodes) {
$marketCode = $node.SelectNodes('filePattern/marketCode').InnerText
$format = $node.SelectNodes('filePattern/format').InnerText
#Trying to concatenate InnerText values here:
$marketCode + '_' + $format
}
}
输出是所需的。

关于xml - PowerShell:如何将InnerText值连接为单个字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64360690/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com