5

#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
Filed in: Columns, Tips and Tricks Tags: , , , ,
© 2018 PowerShell Magazine. All rights reserved. XHTML / CSS Valid.
Proudly designed by Theme Junkie.
%d bloggers like this: