Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Given the following xml:

<foo bar="&amp;foobar">some text</foo>

I need to get the value of the bar attribute without it being unescaped. Every method I've tried thus far in PowerShell results in this value:

&foobar

Rather than this:

&amp;foobar

I need the latter, as I need the literal, properly escaped value to persist.

If I do this:

[xml]$xml = "<foo bar='&amp;foobar'>some text</foo>"
$xml.foo.bar

The attribute value is unescaped (i.e. &foobar).

If I do this:

$val = $xml | select-xml "/foo/@bar"
$val.Node.Value

The attribute value is unescaped (i.e. &foobar).

What is the best way to ensure that I get the original, escaped value of an attribute with PowerShell?

like image 638
kiprainey Avatar asked Dec 20 '12 15:12

kiprainey


2 Answers

[Security.SecurityElement]::Escape($xml.foo.bar)
like image 99
Shay Levy Avatar answered Nov 03 '22 06:11

Shay Levy


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()
like image 22
kiprainey Avatar answered Nov 03 '22 07:11

kiprainey