简体   繁体   中英

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)

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;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM