How to encode a string for use in xml

The Problem

When you are constructing xml using the classes from the System.Xml namespace you really don’t need to worry about encoding characters, you simply set the value of an XmlAttribute and the rest is taken care of for you.

There are some instances however where you find yourself constructing a string representation of xml. In my case I was trying to set the content of a dynamic menu in the Office Ribbon. In it’s simplest form what I needed to do was give Office a string which contained the xml definition of all the buttons on my dynamic menu.

This is easy enough to do you just need to be careful and ensure you write valid xml, right? Of course that’s right. But the bit that always gets me is knowing which characters need to be encoded (or escaped), and how to do it.

The Solution

If you’ve already gone to the overhead of creating a XmlDocument or performance of creating an XmlDocument in memory is not an issue, then I like the simplicity of this solution.

/// <summary>
/// Returns an encoded version of the string passed in that
/// is suitable for use in constructing valid XML
/// </summary>
/// <param name="stringToEncode">The string to encode</param>
/// <returns>The string with any reserved chars encoded for use in xml</returns>
public static string EncodeStringForUseInXml(string stringToEncode)
     XmlDocument doc = new XmlDocument();
     XmlElement element = doc.CreateElement("temp");
     element.InnerText = stringToEncode;
     return element.InnerXml;

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Create a website or blog at

Up ↑

%d bloggers like this: