我有此PowerShell脚本,可用于解析XML文件的不同方面。因此,我想检索特定XML节点的值并将其保存到变量中。我想选择的这个节点在XML文件中存在多次,因此我需要能够提及要检索的节点的特定编号。
XML文件:
<lvl1>
<lvl2>
<lvl3>
<lvl4>test1</lvl4>
<lvl4>test2</lvl4>
<lvl4>test3</lvl4>
</lvl3>
</lvl2>
</lvl1>
我尝试过的Powershell脚本:
[xml] $response = get-content "FilePath\Resp.xml"
[string] $Var = $response.SelectSingleNode('lvl1/lvl2/lvl3/lvl4[2]').InnerText
[xml] $response = get-content "FilePath\Resp.xml"
$Var = $response.lvl1.lvl2.lvl3.lvl4[2].'#text'
BACON本质上在对问题的评论中提供了关键指针:
使用PowerShell的点符号 n 直接返回叶元素(仅具有文本子节点的元素)的文本内容,所以有不需要'.#text'
:
# Note: `.lvl4` is an *array* provided by PowerShell, so the index is
# 0-based. Therefore, [2] retrieves the *3rd* element.
$response.lvl1.lvl2.lvl3.lvl4[2] # -> 'test3'
请注意,PowerShell将多个lvl4
元素公开为array,因此该数组中的indexing是0
-based。]
您基于XPath的命令应按原样工作,但请注意XPath中的索引是基于1
的,因此[2]
将引用2nd元素:] >
$response.SelectSingleNode('lvl1/lvl2/lvl3/lvl4[2]').InnerText # -> 'test2'
# Equivalent commands:
$response.SelectSingleNode('lvl1/lvl2/lvl3/lvl4[2]').'#text'
$response.SelectSingleNode('lvl1/lvl2/lvl3/lvl4[2]/text()').Value