#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;
& &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: , , , ,

5 Responses to "#PSTip Replacing invalid XML characters"

  1. Roger Goins says:

    What if I have a XML config file that contains the escaped character? When I read it in and make a replacement to some text, I use the xml.save method. This replaces the escaped character with the actual character.
    Example: (part of the xml config file) provider connection string="data source=…
    I change the server name after ‘data source=’ then save. The file will now contain:
    provider connection string=”data source=…
    This causes a problem when the service tries to read the file. Thoughts?

  2. Roger Goins says:

    Looks like the comment parsed out the escape sequence. The quote before ‘data source’ should be the escape sequence, not an actual quote.

  3. Roger Goins says:

    Nevermind… I was confused. Sorry for the crazy comment.

Leave a Reply

Submit Comment

© 0866 PowerShell Magazine. All rights reserved. XHTML / CSS Valid.
Proudly designed by Theme Junkie.
%d bloggers like this: