这是代码的简化版本:
$CSVpath = "G:\1.csv"
$xmlPath = "G:\1.xml"
# This is a more robust (and faster) way to load XML files.
($xmlDoc = [xml]::new()).Load((Convert-Path $xmlPath))
# Get all column names
$columnNames = (Get-Content -First 1 $CSVpath) -split ',' -replace '"'
Write-Host "Column count: $($columnNames.Count); names: $columnNames"
foreach ($columnName in $columnNames) {
@($xmlDoc.enum_types.enum_type.Where({ $_.field_name -eq $columnName }, 'First').
items).ForEach({ $_.item }).Where({ $_.id -eq 1 }).value
}
它为我输出以下内容:
Column count: 2; names: Test1 Test2
A
A
Note:
以上仅适用于列名CSV 文件的,带有硬编码的 id
价值 - 就像你自己的尝试一样。
To 根据以下内容从 XML 中提取数据data在 CSV 中并根据填充的列:
$CSVpath = "G:\1.csv"
$xmlPath = "G:\1.xml"
# This is a more robust (and faster) way to load XML files.
($xmlDoc = [xml]::new()).Load((Convert-Path $xmlPath))
# Import the CSV.
$csvRows = Import-Csv $CSVpath
# Get the column names.
$columnNames = $csvRows[0].psobject.Properties.Name
foreach ($csvRow in $csvRows) {
foreach ($columnName in $columnNames) {
$id = $csvRow.$columnName
if (-not $id) { continue }
@($xmlDoc.enum_types.enum_type.Where({ $_.field_name -eq $columnName }, 'First').
items).ForEach({ $_.item }).Where({ $_.id -eq $id }).value
}
}
注意:对于这样的嵌套循环,绝对值得考虑切换到 XPath 解决方案.SelectSingleNode()
以提高性能。
[1] .ForEach()
and .Where()
should work on any object, even scalar (non-collection) ones, but in Windows PowerShell that doesn't work with certain types, such as XML elements.