我不确定标题对我需要回答的问题是否正确,但现在开始了。
我需要获取嵌套在一个节点下的<Amount>值,其中<Type>节点包含一个特定的值。
具体来说,<BurialFund>类型下的金额。
我使用的脚本(在XML示例下面)只返回来自<Asset>节点的第一个金额,因此我需要一种方法来根据<Type>值指定要从哪个节点提取数据。
我相信这是我需要帮助的线路:$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\Burial\'
$manifest = 'C:\Users\username\Documents\XML\Burial\' + (Get-Date -Format yyyyMMdd) + '.csv'
Get-ChildItem -Path $dir -Filter *xml | ForEach-Object {
# Retrieve values from specified nodes.
$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 values were retrieved succesfully.
if ($interviewDate -and $burial -and $dob -and $lastName -and $firstName) {
# Create a custom PSObject and set the values to corresponding properties.
# Out-String Trim used to eliminate System.Object[] error.
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 values.
Clear-Variable interviewDate, burial, dob, lastName, firstName
# Set order of columns.
# Export data to the CSV file.
} | Select-Object InterviewDate, Burial, DOB, LastName, FirstName | Export-Csv -Path $manifest -NoTypeInformation -append发布于 2022-08-10 22:25:58
只关注从xml中提取目标量,并使用SelectSingleNode而不是Select,尝试如下:
$xml = [xml]'your xml above'
$expression = "//Asset[Type='BurialFund']/Amount";
$target = $xml.SelectSingleNode($expression);
echo $target.InnerText输出:
5000发布于 2022-08-11 12:33:58
或者简单地使用点符号,比如:
[xml]$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>
'@
($xml.AssetParent.Assets.Asset | Where-Object {$_.Type -eq 'BurialFund'}).Amount结果:5000
https://stackoverflow.com/questions/73312677
复制相似问题