Reputation: 11
I need to set an xml value to the newline escape code
<Variable>Foo 
 Bar</Variable>
I'm using get-content to create an xml object and trying to assign the variable using the following method
$qux = $("Foo 
 Bar")
$xml = [xml](Get-Content $xmlpath)
$xml.Variable = $qux
$xml.Save($tlpath)
$xml.Close
I've tried using & in place of &, using single quotes and a backslash and I can't seem to prevent the code from converting the & to & and spitting out the following xml
<Variable>Foo &#xA; Bar</Variable>
What is the best way to get around powershell converting the escape character?
Upvotes: 1
Views: 2650
Reputation: 73506
Assign a normal multiline string:
$xml.Variable = "Foo`nBar"
Or access the variable as an XML node and assign an XML string which will be transformed into normal newline characters:
$xml['Variable'].innerXml = "Foo
Bar"
.NET framework XML class saves new line characters as actual new lines inside text nodes, and as entities when inside attributes. It means that we'll need to postprocess the XML output before writing it:
$xml = [xml]::new()
$xml.Load('r:\1.xml')
$xml.Variable = "Foo`nBar"
# encode 
 inside text nodes and both 
 
 inside attributes
$xmlSettings = [Xml.XmlWriterSettings]::new()
$xmlSettings.NewLineHandling = [Xml.NewLineHandling]::Entitize
$sb = [Text.StringBuilder]::new()
$xmlWriter = [System.Xml.XmlWriter]::Create($sb, $xmlSettings)
$xml.Save($xmlWriter)
$sb.ToString().Replace("`n", '
') | Out-File r:\2.xml -Encoding utf8
Note: in PowerShell 2.0 instead of [some.class]::new()
use New-Object some.class
Upvotes: 1