Thursday, July 20, 2006

XML Encode & Decode

Whenever we use XML in your application, we might be required to encode and decode the data which we are passing in the XML since the data may contain some special charecters like XML tags. The charecters '<', '>', '&' and '"' may have to be replaced. I use these methods to encode and decode XML strings.


public string XMLEncode(string Value)
{
return Value.Replace ("&", "&amp;").Replace("'", "&apos;").Replace ("\"", "&quot;").Replace ("<", "&lt;").Replace(">", "&gt;");
}

public string XMLDecode(string Value)
{
return Value.Replace ("&amp;", "&").Replace("&apos;", "'").Replace("&quot;", "\"").Replace ("&lt;", "<").Replace ("&gt;", ">");
}

4 Comments:

Anonymous Anonymous said...

What about XML encoded characters (e.g. "{")?

8:10 AM  
Blogger Unknown said...

Hi,
Ive seen that you encoded the quote symbol but while decoding you didn't decode the quote

11:51 PM  
Blogger Ganesh Ramamurthy said...

Thanks Keith for pointing it out. I have updated the post.

Happy Programming.

11:56 PM  
Anonymous Jeff Wenger said...

I have moved the ampersand decoding to the last position to avoid a situation where there is double-decoding as follows:

&lt;Name&gt;JACK &amp;&amp; JILL&amp;lt;SAMPLE&lt;/Name&gt;

In this example, the < before the SAMPLE is improperly decoded.

11:40 AM  

Post a Comment

<< Home