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

PowerShell XML:根据Type节点值获取对应Amount节点值

问题:筛选XML中指定Type对应的Amount值

我是PowerShell新手,需要从XML文件中提取同级节点<Type>值为“BurialFund”的<Amount>节点数值。目前脚本仅能返回<Asset>节点下的第一个<Amount>值,需调整XPath语句实现按<Type>值筛选目标节点。脚本其他功能(读取指定文件夹XML文件、提取其他节点值并导出至CSV)均正常,需修改的代码行如下:

$burial = Select-Xml -XPath '//AssetParent/Assets/Asset/Amount'

XML片段示例

<AssetParent>
    <Assets>
        <Asset>
            <Type>CheckingAccounts</Type>
            <Amount>100</Amount>
        </Asset>
        <Asset>
            <Type>SavingsAccounts</Type>
            <Amount>200</Amount>
        </Asset>
        <Asset>
            <Type>BurialFund</Type>
            <Amount>5000</Amount>
        </Asset>
    </Assets>
</AssetParent>

当前使用的脚本

# 设置脚本读取文件和写入结果的目录
$dir = 'C:\Users\username\Documents\XML\BurialAssetExclusion\'
$manifest = 'C:\Users\username\Documents\XML\BurialAssetExclusion\' + (Get-Date -Format yyyyMMdd) + '.csv'

# 处理XML文件
Get-ChildItem -Path $dir -Filter *xml | ForEach-Object {

  # 从指定节点获取值
  $interviewDate = Select-Xml -XPath '//CurrentDate' -Path $_.FullName -ErrorAction SilentlyContinue
  $burial = Select-Xml -XPath '//AssetParent/Assets/Asset/Amount' -Path $_.FullName -ErrorAction SilentlyContinue
  $dob = Select-Xml -XPath '//DOB' -Path $_.FullName -ErrorAction SilentlyContinue
  $lastName = Select-Xml -XPath '//LastName' -Path $_.FullName -ErrorAction SilentlyContinue
  $firstName = Select-Xml -XPath '//FirstName' -Path $_.FullName -ErrorAction SilentlyContinue

  # 如果成功获取到所有值
  if ($interviewDate -and $burial -and $dob -and $lastName -and $firstName) {

    # 创建自定义PSObject并为属性赋值
    # 使用Out-String Trim消除System.Object[]错误
    New-Object PSObject -Property @{
      InterviewDate = ($interviewDate.Node.InnerText | Out-String).Trim()
      Burial = ($burial.Node.InnerText | Out-String).Trim()
      DOB = ($dob.Node.InnerText | Out-String).Trim()
      LastName = ($lastName.Node.InnerText | Out-String).Trim()
      FirstName = ($firstName.Node.InnerText | Out-String).Trim()
    }
  }
  
  # 清空变量
  Clear-Variable interviewDate, burial, dob, lastName, firstName
  
    # 设置列顺序并导出数据到CSV文件
  } | Select-Object InterviewDate, Burial, DOB, LastName, FirstName | Export-Csv -Path $manifest -NoTypeInformation -append

解决方案

只需修改$burial对应的XPath语句,通过条件筛选出<Type>为“BurialFund”的<Asset>节点,再获取其下的<Amount>:

$burial = Select-Xml -XPath '//AssetParent/Assets/Asset[Type="BurialFund"]/Amount' -Path $_.FullName -ErrorAction SilentlyContinue

XPath逻辑说明

  • //AssetParent/Assets/Asset:定位到所有<Asset>节点
  • [Type="BurialFund"]:筛选出子节点<Type>文本等于“BurialFund”的<Asset>
  • /Amount:获取该<Asset>下的<Amount>节点

修改后,脚本就能准确提取到对应类型的金额数值。

内容的提问来源于stack exchange,提问作者Tom Christman

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 14:06:18