如何通过 id 替换(Id 值从 XML 中获取)并放入 CSV、powershell [英] How to get replace by id (Id value get from XML) and put into CSV, powershell
本文介绍了如何通过 id 替换(Id 值从 XML 中获取)并放入 CSV、powershell的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用
解决方案
您需要修改 foreach
循环以更新(内存中的)CSV 行(对象),然后将它们保存回 CSV 文件:
# ...foreach ($csvRows 中的 $csvRow) {foreach($columnNames 中的 $columnName){$id = $csvRow.$columnNameif (-not $id) { 继续 }$newId = @($xmlDoc.enum_types.enum_type.Where( { $_.field_name -eq $columnName }, 'First').items).ForEach( { $_.item }).Where( { $_.id -eq $id }).value# 更新相关的 CSV 字段.# 注意:如果没有找到 ID,`$newId` 包含 $null# 并且该字段将被清空.$csvRow.$columnName = $newId}}# 导出更新的 CSV 行(对象)# 注意:这会写回输入的 CSV 文件.# 一定要先备份原件.# 根据需要调整 -Encoding.$csvRows |导出-Csv -NoTypeInformation -Encoding utf8 $CSVpath
I'm using below code from this answer to get value from id and I need to replace value of id in csv from xml by and save csv files :
$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
}
}
XML:
<enum_types>
<enum_type field_name="Test1">
<items>
<item>
<id>1</id>
<value>A</value>
</item>
</items>
</enum_type>
<enum_type field_name="Test2">
<items>
<item>
<id>1</id>
<value>A</value>
</item>
</items>
</enum_type>
</enum_types>
Please find below CSV Files for replace value ID value from above xml:
解决方案
You need to modify the foreach
loop to update the (in-memory) CSV rows (objects), and then save them back to a CSV file:
# ...
foreach ($csvRow in $csvRows) {
foreach ($columnName in $columnNames) {
$id = $csvRow.$columnName
if (-not $id) { continue }
$newId = @($xmlDoc.enum_types.enum_type.Where( { $_.field_name -eq $columnName }, 'First').
items).ForEach( { $_.item }).Where( { $_.id -eq $id }).value
# Update the relevant CSV field.
# Note: If the ID wasn't found, `$newId` contains $null
# and the field will be blanked out.
$csvRow.$columnName = $newId
}
}
# Export the updated CSV rows (objects)
# Note: This writes back to the input CSV file.
# Be sure to make a backup of the original first.
# Adjust -Encoding as needed.
$csvRows | Export-Csv -NoTypeInformation -Encoding utf8 $CSVpath
这篇关于如何通过 id 替换(Id 值从 XML 中获取)并放入 CSV、powershell的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文