#PSTip Replacing invalid XML characters

Note: This tip requires PowerShell 2.0 or above.

When authoring XML documents, some of the data you will use in your tags are considered invalid. For example, you might want to include an ampersand character in one of the tags:

<Tag>& $foo</Tag>

However, the ‘&’  character is invalid and using it as is will generate an exception. Instead, we need to replace it with its escaped equivalent. The following table lists the characters that needs to be escaped.

Invalid character Replace with
< &lt;
> &gt;
&quot;
&apos;
& &amp;

Making sure a character is not invalid by looking at the value of a string is not that difficult but what if you don’t have control over the value or the content of the tag is passed via a variable? This is where the SecurityElement.Escape method comes into play. Similarly to the Regex.Escape method, SecurityElement.Escape lets you replace invalid characters with their valid values. 

PS> $var = '& $foo'
PS> [System.Security.SecurityElement]::Escape($var)

&amp; $foo

About the author: Shay Levy

Shay Levy is a Co-founder and editor of the PowerShell Magazine. He is a multiple-year recipient of the Microsoft MVP award, and a Microsoft Certified Trainer (MCT). Shay often covers PowerShell related topics on his blog and you can also follow him on Twitter at @ShayLevy

Related Posts