XML Encode in C#
Ever wanted to have a little method to encode xml content? You know when you have a < but you want it to appear as < - that kind of thing.
Well We can leverage existing base classes to achieve this quite easily as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
namespace XmlEncode
{
class Program
{
static void Main(string[] args)
{
string text1 = "2 & 4";
string text2 = "2 < 4";
Console.WriteLine(XMLEncode(text1));
Console.WriteLine(XMLEncode(text2));
Console.Read();
}
public static string XMLEncode(string val)
{
if (val.Length == 0)
{
return string.Empty;
}
XmlDocument xmldoc = new XmlDocument();
XmlElement element = xmldoc.CreateElement("E");
element.InnerText = val;
return element.InnerXml;
}
}
}
And thats it! Any comments welcome as always.