home / software / tips and tricks / How to deal with the escape charectors in string when it is converting to xml?

How to deal with the escape charectors in string when it is converting to xml?

Updated:  08/11/2014 04:08 AM
Author:  Shiju Mathews

Status:    Resolved.


XML encoding is necessary when we are saving XML text in an XML document. Basically there are five characters , that we need to deal with.

Escape CharacterXml Value
< &lt;
> &gt;
" &quot;
' &apos;
&&amp;


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

1. Use string.Replace() to replace the escape charters.


2. Use 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 ( ' ).

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.

4. System.Xml.XmlTextWriter Using XmlTextWriter is the safest way to create an xml document.
Tags: How to deal with the escape charectors in string when it is converting to xml?
Updated on: November 2024