Reputation: 51
I am editing a config file using PowerShell. I need to output the following exactly like this: "<FieldDelimiter>	</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>&#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>	</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
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 "&" with "&" like below:
$config = (Get-Content $configFilePath)
$newConfig = $config.Replace('&', '&')
Out-File -FilePath $configFilePath -InputObject $newConfig
Upvotes: 1
Reputation: 29470
You can escape the ampersand &
:
<FieldDelimiter>&#9;</FieldDelimiter>
As a test, I created this script:
$x = [xml]@"
<DeviceInfo>
<FieldDelimiter>&#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>&#9;</FieldDelimiter>
<UseFormattedValues>True</UseFormattedValues>
<NoHeader>True</NoHeader>
<FileExtension>txt</FileExtension>
</DeviceInfo>
# C:\Temp> $x = [xml](gc .\testEscape.xml)
# C:\Temp> $x.DeviceInfo.FieldDelimiter
	
Upvotes: 0