Andrew Holtsclaw
Andrew Holtsclaw

Reputation: 51

Output raw special characters in XML from PowerShell

I am editing a config file using PowerShell. I need to output the following exactly like this: "<FieldDelimiter>&#9;</FieldDelimiter>". It, of course, wants to translate the tab character and write a tab (white space). The closest I've gotten is for it to output: "<FieldDelimiter>&amp;#9;</FieldDelimiter>", which is no good. How can I get it to write to the file the ampersand itself?

I'm reading in the file:

[xml]$xml = (Get-Content $configFilePath)  
...(skip some code)...

appending some child elements:

$configuration = $xml.CreateElement("Configuration")
$newExtension = $xml.CreateElement("Extension")

$configuration.InnerXml = "
            <DeviceInfo>
                <FieldDelimiter>&#9;</FieldDelimiter>
                <UseFormattedValues>True</UseFormattedValues>
                <NoHeader>True</NoHeader>
                <FileExtension>txt</FileExtension>
            </DeviceInfo>"

$newExtension.AppendChild($configuration)
...(more code skipped)...
$xml.Configuration.Extensions.Render.InsertAfter($newExtension, $csvNode)

then saving the file.

$xml.Save($configFilePath)

Upvotes: 2

Views: 2435

Answers (2)

Andrew Holtsclaw
Andrew Holtsclaw

Reputation: 51

Update:
I was not able to get an answer on how to output simply an ampersand character in the XML without encoding, and I was running out of time on the project, so here's what I did that worked (not the preferred answer, but it works).

I read the file again and replaced the "&amp;" with "&" like below:

$config = (Get-Content $configFilePath)
$newConfig = $config.Replace('&amp;', '&')
Out-File -FilePath $configFilePath -InputObject $newConfig

Upvotes: 1

zdan
zdan

Reputation: 29470

You can escape the ampersand &:

<FieldDelimiter>&amp;#9;</FieldDelimiter>

As a test, I created this script:

$x = [xml]@"
<DeviceInfo>
  <FieldDelimiter>&amp;#9;</FieldDelimiter>
  <UseFormattedValues>True</UseFormattedValues>
  <NoHeader>True</NoHeader>
  <FileExtension>txt</FileExtension>
</DeviceInfo>
"@
$x.Save("c:\temp\testEscape.xml")

Then I test reading resulting file:

# C:\Temp> gc .\testEscape.xml
<DeviceInfo>
  <FieldDelimiter>&amp;#9;</FieldDelimiter>
  <UseFormattedValues>True</UseFormattedValues>
  <NoHeader>True</NoHeader>
  <FileExtension>txt</FileExtension>
</DeviceInfo>
# C:\Temp> $x = [xml](gc .\testEscape.xml)
# C:\Temp> $x.DeviceInfo.FieldDelimiter
&#9;

Upvotes: 0

Related Questions