String escape into XML String escape into XML xml xml

String escape into XML


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;}


EDIT: You say "I am concatenating simple and short XML file and I do not use serialization, so I need to explicitly escape XML character by hand".

I would strongly advise you not to do it by hand. Use the XML APIs to do it all for you - read in the original files, merge the two into a single document however you need to (you probably want to use XmlDocument.ImportNode), and then write it out again. You don't want to write your own XML parsers/formatters. Serialization is somewhat irrelevant here.

If you can give us a short but complete example of exactly what you're trying to do, we can probably help you to avoid having to worry about escaping in the first place.


Original answer

It's not entirely clear what you mean, but normally XML APIs do this for you. You set the text in a node, and it will automatically escape anything it needs to. For example:

LINQ to XML example:

using System;using System.Xml.Linq;class Test{    static void Main()    {        XElement element = new XElement("tag",                                        "Brackets & stuff <>");        Console.WriteLine(element);    }}

DOM example:

using System;using System.Xml;class Test{    static void Main()    {        XmlDocument doc = new XmlDocument();        XmlElement element = doc.CreateElement("tag");        element.InnerText = "Brackets & stuff <>";        Console.WriteLine(element.OuterXml);    }}

Output from both examples:

<tag>Brackets & stuff <></tag>

That's assuming you want XML escaping, of course. If you're not, please post more details.