我目前正在使用SelectNodes()
对XML文件中的某些文本节点执行替换操作,并定义需要更新的每个节点 - 这样可以正常工作。这非常繁琐(多行但每次都有相同的替换操作)。我想仅对该文件中的 TEXT 节点执行替换操作。
这就是我现在所拥有的:
$path = "C:\Dump\TEST"
$Files = Get-Childitem -Path $path -File -Include test_file_1.xml -Name
foreach ($File in $Files) {
$xml = [xml](Get-Content $path\$File)
$xml.SelectNodes('//ContactDetailsRow/Notes') | ForEach-Object {
$_.'#text' = $_.'#text'.Replace("\", "\\").Replace("`b", "\b")
}
$xml.SelectNodes('//AddressesRow/Notes') | ForEach-Object {
$_.'#text' = $_.'#text'.Replace("\", "\\").Replace("`b", "\b")
}
$xml.Save("$path\$File")
}
我曾尝试使用xpath这样做,这会引发错误。
$path = "C:\Dump\TEST"
$Files = Get-Childitem -Path $path -File -Include test_file_1.xml -Name
foreach ($File in $Files) {
$xml = [xml](Get-Content $path\$File)
$xml.SelectNodes('//text()') | ForEach-Object {
$_.'#text' = $_.'#text'.Replace("\", "\\").Replace("`b", "\b")
}
$xml.Save("$path\$File")
}
错误就是这个
You cannot call a method on a null-valued expression. At C:\Dump\test12.ps1:14 char:13 + $_.'#text' = $_.'#text'.Replace("\", "\\").Replace("`b", "\b") + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [], RuntimeException + FullyQualifiedErrorId : InvokeMethodOnNull
这是一个示例XML文件:
<?xml version="1.0" encoding="UTF-8"?>
<OrganisationUnits>
<OrganisationUnitsRow num="21">
<OrganisationId>ORG1</OrganisationId>
<OrganisationName>ORG 1 TEST</OrganisationName>
<Addresses>
<AddressesRow num="1">
<AddressId>E41002</AddressId>
</AddressesRow>
</Addresses>
<ContactDetails>
<ContactDetailsRow num="1">
<ContactValue>info@gmail.com</ContactValue>
<StartDate>2000-03-11</StartDate>
<Main>N</Main>
<Notes>TEST \ NOTES</Notes>
</ContactDetailsRow>
</ContactDetails>
<Sector>P</Sector>
<SectorDesc>Private</SectorDesc>
</OrganisationUnitsRow>
</OrganisationUnits>
答案 0 :(得分:1)
PowerShell可以使用本机cmdlet管理XML,以帮助您完成您正在尝试执行的操作。
$path = "C:\Dump\TEST"
$Files = Get-Childitem -path $path -File -include test_file_1.xml -name
foreach ($File in $Files)
{
[xml]$MyXML = Get-Content $File.FullName -raw
Select-Xml -XML $MyXML -XPath '//text()'|% {$_.Node.Value = $_.Node.Value -replace '\\','\\' -replace '`b','\b'}
$MyXML.Save($File.FullName)
}