【发布时间】:2017-10-23 21:25:02
【问题描述】:
我目前正在使用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")
}
错误是这样的
您不能在空值表达式上调用方法。 在 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>
【问题讨论】:
-
//text()->//*[text()]
标签: xml powershell xpath text replace