I want some Moore

Blog about stuff and things and stuff. Mostly about SQL server and .Net
posts - 176, comments - 1796, trackbacks - 33

My Links

SQLTeam.com Links

News

Hi! My name is 
Mladen Prajdić  I'm from Slovenia and I'm currently working as a .Net (C#) and SQL Server developer. I'm a MCP and MCTS for SQL Server. I also speak at local user group meetings and conferences like NT Conference 
Welcome to my blog.

Search this Blog

My Blog Feed via Email


Users Online: who's online

Article Categories

Archives

Post Categories

Cool software

Other Blogs

Other stuff

SQL stuff

Different ways how to escape an XML string in C#

XML encoding is necessary if you have to save XML text in an XML document. If you don't escape special chars the XML to insert will become a part of the original XML DOM and not a value of a node.

Escaping the XML means basically replacing 5 chars with new values.

These replacements are:

< -> &lt;
> -> &gt;
" -> &quot;
' -> &apos;
& -> &amp;

 

Here are 4 ways you can encode XML in C#:

1. string.Replace() 5 times

This is ugly but it works. Note that Replace("&", "&amp;") has to be the first replace so we don't replace other already escaped &.

string xml = "<node>it's my \"node\" & i like it<node>"; encodedXml = xml.Replace("&", "&amp;").Replace("<", "&lt;").Replace(">", "&gt;").Replace("\"", "&quot;").Replace("'", "&apos;"); // RESULT: &lt;node&gt;it&apos;s my &quot;node&quot; &amp; i like it&lt;node&gt;

 

2. System.Web.HttpUtility.HtmlEncode()

Used for encoding HTML, but HTML is a form of XML so we can use that too. Mostly used in ASP.NET apps. Note that HtmlEncode does NOT encode apostrophes ( ' ).

string xml = "<node>it's my \"node\" & i like it<node>"; string encodedXml = HttpUtility.HtmlEncode(xml); // RESULT: &lt;node&gt;it's my &quot;node&quot; &amp; i like it&lt;node&gt;

 

3. System.Security.SecurityElement.Escape()

In Windows Forms or Console apps I use this method. If nothing else it saves me including the System.Web reference in my projects and it encodes all 5 chars.

string xml = "<node>it's my \"node\" & i like it<node>"; string encodedXml = System.Security.SecurityElement.Escape(xml); // RESULT: &lt;node&gt;it&apos;s my &quot;node&quot; &amp; i like it&lt;node&gt;

 

4. System.Xml.XmlTextWriter

Using XmlTextWriter you don't have to worry about escaping anything since it escapes the chars where needed. For example in the attributes it doesn't escape apostrophes, while in node values it doesn't escape apostrophes and qoutes.

string xml = "<node>it's my \"node\" & i like it<node>"; using (XmlTextWriter xtw = new XmlTextWriter(@"c:\xmlTest.xml", Encoding.Unicode)) { xtw.WriteStartElement("xmlEncodeTest"); xtw.WriteAttributeString("testAttribute", xml); xtw.WriteString(xml); xtw.WriteEndElement(); } // RESULT: /* <xmlEncodeTest testAttribute="&lt;node&gt;it's my &quot;node&quot; &amp; i like it&lt;node&gt;"> &lt;node&gt;it's my "node" &amp; i like it&lt;node&gt; </xmlEncodeTest> */

 

Each of the four ways is different, so use each one where you fell appropriate. You can't go wrong with SecurityElement though. :)

 

kick it on DotNetKicks.com
 

Print | posted on Tuesday, October 21, 2008 10:43 AM

Feedback

# re: Different ways how to escape an XML string in C#

Good post. I did not know about System.Security.SecurityElement.Encode().
10/22/2008 12:32 PM | Homer S

# re: Different ways how to escape an XML string in C#

To be totally safe, besides escaping the 5 chars above there are other chars you need to worry about. There are some chars that are simply forbidden in XML. See: http://www.w3.org/TR/xml11/#charsets
11/5/2008 6:34 PM | Jesse

# re: Different ways how to escape an XML string in C#

Thanks for the breakdown. I like to have optons.
12/5/2008 8:23 AM | Foo JH

# re: Different ways how to escape an XML string in C#

It's Good
12/22/2008 10:04 AM | Sibaram Pala

# re: Different ways how to escape an XML string in C#

I can't stop XmlText from converting chars.. I'm to the point of automating a query replace after my XML doc is created, All help is greatly apprecaited.. In my code snipet below i need to maintain the < > chars in my CData..
XmlElement fieldNodeBody = xmlDoc.CreateElement("field");
fieldNodeBody.SetAttribute("name", "body");
XmlText fieldNodeBodyText = xmlDoc.CreateTextNode("field");
fieldNodeBodyText.Value = "<![CDATA[" + adoDR[5].ToString() + "]]>";
fieldNodeBody.AppendChild(fieldNodeBodyText);
contentNode.AppendChild(fieldNodeBody);
Thanks
rich
3/5/2009 2:06 AM | Rich Trawinski

# re: Different ways how to escape an XML string in C#

Another way is simply to use the InnerText and InnerXml properties of an XmlDOM node.

string xml = "<node>it's my \"node\" & i like it<node>";
XmlDocument xDoc = new XmlDocument();
XmlElement xElem = xDoc.CreateElement("Content");
xElem.InnerText = xml;
MessageBox.Show(xElem.InnerXml); // Get escaped content
MessageBox.Show(xElem.InnerText); // Get XML
3/11/2009 2:32 AM | Charles Young

# re: Different ways how to escape an XML string in C#

The most straightforward and safe way is to use XmlWriter.

string xml = "<node>it's my \"node\" & i like it<node>";
StringBuilder encodedString = new StringBuilder (xml.Length);
using (var writer = XmlWriter.Create(encodedString))
{
writer.WriteString(xml);
}

using XmlDocument is costly, and using HtmlEncode is incorrect - HTML will not encode ' and WILL encode e as &eacute;, etc.
4/19/2009 9:02 AM | iouri

# re: Different ways how to escape an XML string in C#

Thanks keep it up :)
6/22/2009 3:31 PM | Chirag

# re: Different ways how to escape an XML string in C#

I personally like the simplicity of solution # 1 but wouldn't want to create a dependency from System.Security just to use the System.Security.SecurityElement.Escape(string) method.

I reflected this method and it does something similar to the solution #1.

private static readonly char[] s_escapeChars = new char[] { '<', '>', '"', '\'', '&' };
private static readonly string[] s_escapeStringPairs = new string[] { "<", "&lt;", ">", "&gt;", "\"", "&quot;", "'", "&apos;", "&", "&amp;" };

/// <summary>
/// Escapes the specified text.
/// </summary>
/// <param name="str">The text to escape.</param>
/// <returns>An escaped string.</returns>
public static string Escape(string str)
{
if (str == null)
{
return null;
}
StringBuilder builder = null;
int length = str.Length;
int startIndex = 0;
while (true)
{
int num2 = str.IndexOfAny(s_escapeChars, startIndex);
if (num2 == -1)
{
if (builder == null)
{
return str;
}
builder.Append(str, startIndex, length - startIndex);
return builder.ToString();
}
if (builder == null)
{
builder = new StringBuilder();
}
builder.Append(str, startIndex, num2 - startIndex);
builder.Append(GetEscapeSequence(str[num2]));
startIndex = num2 + 1;
}
}

private static string GetEscapeSequence(char c)
{
int length = s_escapeStringPairs.Length;
for (int i = 0; i < length; i += 2)
{
string str = s_escapeStringPairs[i];
string str2 = s_escapeStringPairs[i + 1];
if (str[0] == c)
{
return str2;
}
}
return c.ToString();
}
6/26/2009 3:14 PM | Javier Callico

Post Comment

Title  
Name  
Email
Url
Comment   
Please add 3 and 5 and type the answer here:

Powered by: