【问题标题】:Replace value in text only nodes替换纯文本节点中的值
【发布时间】: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


【解决方案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)
}

【讨论】:

    猜你喜欢
    • 2015-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-04
    • 2010-12-02
    • 2018-07-18
    • 2014-08-27
    • 1970-01-01
    相关资源
    最近更新 更多