Marley Kudiabor
Marley Kudiabor

Reputation: 11

How to set xml value to an escape character in powershell

I need to set an xml value to the newline escape code

<Variable>Foo &#xA; Bar</Variable>

I'm using get-content to create an xml object and trying to assign the variable using the following method

$qux = $("Foo &#xA; Bar")
$xml = [xml](Get-Content $xmlpath)

$xml.Variable = $qux 

$xml.Save($tlpath)
$xml.Close 

I've tried using &amp in place of &, using single quotes and a backslash and I can't seem to prevent the code from converting the & to &amp and spitting out the following xml

<Variable>Foo &amp;#xA; Bar</Variable>

What is the best way to get around powershell converting the escape character?

Upvotes: 1

Views: 2650

Answers (1)

woxxom
woxxom

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&#xA;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 &#xD; inside text nodes and both &#xA; &#xD; 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", '&#xA;') | Out-File r:\2.xml -Encoding utf8

Note: in PowerShell 2.0 instead of [some.class]::new() use New-Object some.class

Upvotes: 1

Related Questions