Author - Dave Amour

Dave Amour has used computers for as long as he can remember and intially started out as an IT trainer delivering a range of IT courses but for the last 11 years has been focusing on the arena of web application development. He was worked for numerous companies over the years and is currently working for Audacs Software Ltd. Dave is also a keen squash player and an active and sucessful member of Experts Exchange

Please feel free to submit any constructive comments which you can do at the bottom of this page.

Dave may be available for programming tuition or consultancy work. Contact via dave@audacs.co.uk
Dave Amour - Click to view CV 

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 &lt;  - 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.

Leave a comment

Name

Email (optional and not disclosed)



Email address is not disclosed but just used to alert you of new posts if entered
Word CV
HTML CV
PDF CV
Text CV
CMS Lite
ETraining
Planet Health
Florida Health
the Date Shack
Taylors
Emcat
Emtex
Browne Jacobson
Alliance & Leicester
Baird Leisure
Swarfega
Creature Comforts
Rugeley Chess Club
Katnip
Katmaid
Dudley NHS
Contact Me
Current Status