Tuesday, September 17, 2013

Escaping and Un-escaping Xml

To place text that itself is an Xml document or node within an another Xml document, we must first escape the Xml being inserted. Escaping means converting reserved Xml characters such as < and > to encoded values &lt; and &gt;, respectively.

Escape

// Approach 1
string xml = "<custom>some custom Xml data</custom>";
string xmlEscaped= System.Security.SecurityElement.Escape(xml);
// xmlEscaped==   &lt;custom&gt;some custom Xml data&lt;/custom&gt;
// xmlEscaped can be set as a node value in another Xml doc

// Approach 2
string customXml= "<custom>some custom Xml data</custom>";
using (XmlTextWriter containerXml= new XmlTextWriter(@"c:\containerDoc.xml", Encoding.Unicode))
{
    containerXml.WriteStartElement("Container");
    // WriteString automatically encodes the customXml
    containerXml.WriteString(customXml);
    containerXml.WriteEndElement();
}

Output
<Container>
  &lt;custom&gt;some custom Xml data&lt;/custom&gt;
</Container>

Un-Escape

To read encoded Xml, grab the escaped Xml text from the Container document.

// escapedXml  is obtained from a node in the Container document
string escapedXml = "&lt;custom&gt;some custom Xml data&lt;/custom&gt;";
string xml = HttpUtility.HtmlDecode(escapedXml);
var doc = new XmlDocument();
doc.LoadXml(xml);

Output
<custom>some custom Xml data</custom>