我有一个源XML文件,我需要验证XML中使用的AddressType
是否与CSV文件中定义的任何一个匹配。如果AddressType
与应用中定义的匹配,则一切正常,不做任何其他事情。
但是,如果AddressType
不匹配,则从XML文件中删除整个提供程序。
所有AddressType
代码都存储在一个有标题行(称为ADDRESS_TYPE
)的CSV中。
ADDRESS_TYPE DR FIS HQ MAIN NOT_STATED OP
这是我的XML文件
<?xml version="1.0" encoding="UTF-8"?>
<OrganisationUnits>
<OrganisationUnitsRow num="10">
<OrganisationId>ORG01</OrganisationId>
<OrganisationName>ORGANISATION 01</OrganisationName>
<Addresses>
<AddressesRow num="1">
<AddressId>E25802</AddressId>
<MainAddress>Y</MainAddress>
<AddressType>HQ</AddressType>
<AddressTypeDesc>Head Office</AddressTypeDesc>
</AddressesRow>
<AddressesRow num="2">
<AddressId>E25899</AddressId>
<MainAddress>N</MainAddress>
<AddressType>MAIN</AddressType>
<AddressTypeDesc>Head Office</AddressTypeDesc>
</AddressesRow>
</Addresses>
</OrganisationUnitsRow>
</OrganisationUnits>
此示例文件有2行,其中AddressType
与CSV文件匹配,因此应保持不变。如果AddressTypes
中的任何一个不匹配,则需要将整个提供商标记为删除。
$File = "C:\Dump\test\edited_file.xml"
$xml = [xml](Get-Content $File)
$address_type_csv = Import-Csv "C:\Dump\address_types.csv"
foreach ($row in $address_type_csv) {
Write-Host "$row" -ForegroundColor White
}
Write-Host $address_type_csv -ForegroundColor White
$field1 = $row.ADDRESS_TYPE
Write-Host "CSV Address Type value = $field1" -ForegroundColor White
$NonMatching = $false
foreach ($UnitRow in $xml.OrganisationUnits.OrganisationUnitsRow) {
$OrgID = $UnitRow.OrganisationId
$OrgName = $UnitRow.OrganisationName
foreach ($AddressRow in $UnitRow.Addresses.AddressesRow) {
$n = $AddressRow.AddressType
Write-Host "XML file AddressType is $n" -ForegroundColor White
if ($field1 -eq $n) {
echo "MATCH. blabla"
Write-Host "MATCH. XML value is $n, Address Type $field1" -ForegroundColor White
} else {
echo "NO MATCH. XML value is $n, Address Type $field1"
Write-Host "NO MATCH. XML value is $n, Address Type $field1" -ForegroundColor White
$UnitRow.parentNode.RemoveChild($UnitRow) >$null
$NonMatching = $true
break
}
}
}
if ($NonMatching) {
$xml.Save("$File")
}
目前,我似乎只是拿起了CSV文件中的最后一行。
PS C:\dump> C:\Dump\test3.ps1 @{ADDRESS_TYPE=DR} @{ADDRESS_TYPE=FIS} @{ADDRESS_TYPE=HQ} @{ADDRESS_TYPE=MAIN} @{ADDRESS_TYPE=NOT_STATED} @{ADDRESS_TYPE=OP} @{ADDRESS_TYPE=DR} @{ADDRESS_TYPE=FIS} @{ADDRESS_TYPE=HQ} @{ADDRESS_TYPE=MAIN} @{ADDRESS_TYPE=NOT_STATED} @{ADDRESS_TYPE=OP} CSV Address Type value = OP XML file AddressType is HQ NO MATCH. XML value is HQ, Address Type OP NO MATCH. XML value is HQ, Address Type OP PS C:\dump>