How to get an escaped xml attribute value in PowerShell without it being unescaped How to get an escaped xml attribute value in PowerShell without it being unescaped powershell powershell

How to get an escaped xml attribute value in PowerShell without it being unescaped


[Security.SecurityElement]::Escape($xml.foo.bar)


Using the sample XML above, each of the following will produce the original, escaped value for the bar attribute:

Using XPath:

$val = $xml | select-xml "/foo/@bar"$val.Node.get_innerXml()

Using PowerShell's native XML syntax:

$xml.foo.attributes.item(0).get_innerXml()


You can also use

[System.Web.HttpUtility]::HtmlEncode($xml.foo.bar).

There is a good answer on html encoding with PowerShell found here: What is the best way to escape html specific characters in a string in (PowerShell)

I'm not sure its any better than @shay's answer because the data is still passing through the XML parser, which returns the unescaped value, which is then passed back through a function to escape it again.

The 'content' has been manipulated in any case and its not 'the original content'. It may be splitting hairs, but in the past when I've needed non-repudiation on what was originally sent, I've stored the whole blob as a text.

It may be acceptable to grab the 'text' by accessing @bar attributes OuterXml property. That OuterXml property will return:

bar="&foobar"

From there, we can do something like:

$xml.foo.attributes['bar'].OuterXml.Split("=")[1]

Which returns:

"&foobar"

I think this is where we want to end up, but you can probably do that in a little nicer way. :)