You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用PowerShell获取XML中KeyStorePath值的问题

解决PowerShell读取XML 节点属性与值的问题

问题场景

现有如下XML文件:

<?xml version="1.0" encoding="UTF-8"?>

<Configure class="some text">
  <!-- Eliminate Old / Insecure / Anonymous Ciphers -->
  <Call name="callname">
    <Arg>
      <Array type="String">
        <Item>.*NULL.*</Item>
      </Array>
    </Arg>
  </Call>
  <!-- Eliminate Insecure Protocols -->
  <Call name="addExcludeProtocols">
    <Arg>
      <Array type="java.lang.String">
        <Item>ITEM</Item>
      </Array>
    </Arg>
  </Call>
  <Set name="KeyStorePath">D:\Folder\Keystore.keystore</Set>
  <Set name="KeyStorePassword">Password</Set>
</Configure>

通过以下代码加载XML后:

[xml]$TestPath = gc XML.xml

执行命令时遇到异常:

  • $TestPath.Configure.Set | Where-Object name -EQ 'KeyStorePath' 无返回结果
  • $TestPath.Configure.Set.Name 仅返回Set,而非预期的KeyStorePath和KeyStorePassword

问题原因

PowerShell处理XML时,直接用.访问节点名称后接的字段,默认指向子节点而非节点的属性。<Set>节点的name是属性而非子节点,因此直接用.name无法获取属性值。

解决方法

1. 筛选指定name属性的节点

通过Attributes集合访问属性值,结合Where-Object筛选:

$TestPath.Configure.Set | Where-Object { $_.Attributes['name'].Value -eq 'KeyStorePath' }

更高效的方式是用XPath直接定位:

$TestPath.SelectSingleNode("//Set[@name='KeyStorePath']")

2. 获取所有节点的name属性值

遍历所有节点,提取属性值:

$TestPath.Configure.Set | ForEach-Object { $_.Attributes['name'].Value }

或用XPath批量获取属性:

$TestPath.SelectNodes("//Set/@name") | ForEach-Object { $_.Value }

3. 获取KeyStorePath的具体值

直接提取目标节点的文本内容:

# 方法1:XPath定位后取InnerText
$keyStorePath = $TestPath.SelectSingleNode("//Set[@name='KeyStorePath']").InnerText

# 方法2:筛选后取InnerText
$keyStorePath = ($TestPath.Configure.Set | Where-Object { $_.Attributes['name'].Value -eq 'KeyStorePath' }).InnerText

内容的提问来源于stack exchange,提问作者Christopher Cass

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 07:15:56