Search code examples
c#.netxmlvisual-studio-2008escaping

String escape into XML


Is there any C# function which could be used to escape and un-escape a string, which could be used to fill in the content of an XML element?

I am using VSTS 2008 + C# + .Net 3.0.

EDIT 1: I am concatenating simple and short XML file and I do not use serialization, so I need to explicitly escape XML character by hand, for example, I need to put a<b into <foo></foo>, so I need escape string a<b and put it into element foo.


Solution

  • public static string XmlEscape(string unescaped)
    {
        XmlDocument doc = new XmlDocument();
        XmlNode node = doc.CreateElement("root");
        node.InnerText = unescaped;
        return node.InnerXml;
    }
    
    public static string XmlUnescape(string escaped)
    {
        XmlDocument doc = new XmlDocument();
        XmlNode node = doc.CreateElement("root");
        node.InnerXml = escaped;
        return node.InnerText;
    }