powershellreplacecontainsselectnodes

Replace text in XML node containg ampersand


I have a PowerShell script in which it is trying to replace the values in an XML file node with a different value.

Example, within the SectorDesc node replace '&' with 'and'.

<?xml version="1.0" encoding="UTF-8"?>
<OrganisationUnits>
  <OrganisationUnitsRow num="8">
    <OrganisationId>ACME24/7HOME</OrganisationId>
    <OrganisationName>ACME LTD</OrganisationName>
    <ContactDetails>
      <ContactDetailsRow num="1">
        <ContactCode>OFFICE</ContactCode>
      </ContactDetailsRow>
    </ContactDetails>
    <Sector>P</Sector>
    <SectorDesc>Private Private &amp; Voluntary</SectorDesc>
  </OrganisationUnitsRow>
</OrganisationUnits>

So this line

<SectorDesc>Private Private &amp; Voluntary</SectorDesc>

woudl now look like this

<SectorDesc>Private Private and Voluntary</SectorDesc>

This is my code so far.

$file = "C:\Dump\test\test.xml"
$xml = [xml](Get-Content $file)
$xml.selectNodes('//SectorDesc/value[contains(.,"text")]')|
                ForEach-Object{$_.'#text' = ($_.'#text' -replace "&amp;","and") } 

$xml.Save("$File")

Solution

  • If you read the xml like this &amp; will get read as just & so you have to replace for &. Also, you can access the node like this:

    $xml.OrganisationUnits.OrganisationUnitsRow.SectorDesc = $xml.OrganisationUnits.OrganisationUnitsRow.SectorDesc -replace '&', 'and'