XML Literals: Escaping Characters
Posted
Fri, Feb 19 2010 18:14
by
Deborah Kurata
In XML, there are several characters that have special meaning, such as the less than (<), greater than (>) and quotation mark ("). If you just type these characters in to your XML literal, your application won’t understand them.
NOTE: All of the code in this post is in Visual Basic since C# does not directly support XML literals.
For example, the following code will not compile. It tries to interpret the less than and greater than signs as XML elements.
In VB:
Dim myXML As XElement = <Product>
<Description>
This is a product that has special characters:
Ampersand: &, Apostrophe: ', Quote: "
Less than: <, Greater than: >"
</Description>
</Product>
To get this code to compile, replace the problematic symbols with HTML character entities:
- < becomes <
- > becomes >
- & becomes &
The resulting code is as follows:
Dim myXML As XElement = <Product>
<Description>
This is a product that has special characters:
Ampersand: &, Apostrophe: ', Quote: "
Less than: <, Greater than: >"
</Description>
</Product> This works, but is not very nice to look at, especially if you are not familiar with HTML character entities.
Another option is to use the RegularExpression Escape and Unescape methods.
NOTE: Be sure to import the System.Text.RegularExpression namespace.
In VB:
Dim s As String= "This is a product that has special characters: " & _
Environment.NewLine & _
"Ampersand: &, Apostrophe: ', Quote: "" " & _
Environment.NewLine & _
"Less than: <, Greater than: >"
Dim myXML As XElement = <Product>
<Description>
<%= Regex.Escape(s) %>
</Description>
</Product>
Dim description As String = Regex.Unescape(myXML.<Description>.Value)
MessageBox.Show(description)
This code results in the following MessageBox:

The only character that you still need to escape is the quotation mark. You can escape it in the string by doubling it ("").
The RegEx.Escape takes care of escaping the necessary characters for the XML string. The RegEx.Unescape takes care of unescaping the characters for viewing.
Enjoy!