views:

1315

answers:

5
+4  A: 

Not a single way, but here are a few:

http://weblogs.sqlteam.com/mladenp/archive/2008/10/21/Different-ways-how-to-escape-an-XML-string-in-C.aspx

marcc
The article mentions many alternatives, but the one that's usually the right answer is XmlWriter.
Steven Sudit
Cool, Steven and marcc, how to un-escape?
George2
I bet if you used the XmlTextWriter class (as Steven recommends), you could you the XmlTextReader class to unescape.
marcc
@marcc: Yes, that's exactly what I'd recommend.
Steven Sudit
+5  A: 

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 &amp; stuff &lt;&gt;</tag>

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

Jon Skeet
Thanks Jon, I have put more details into my original post EDIT 1 section. Appreciate if you could give me some comments and advice. :-)
George2
"after XML escaping" -- you mean? Could you speak in some other words please? English is not my native language. :-)
George2
George2
@George2: You ask the XElement for its Value, or the XmlElement for its InnerText.
Jon Skeet
+2  A: 
public static string XmlEscape(string unescaped)
{
    XmlDocument doc = new XmlDocument();
    var node = doc.CreateElement("root");
    node.InnerText = unescaped;
    return node.InnerXml;
}

public static string XmlUnescape(string escaped)
{
    XmlDocument doc = new XmlDocument();
    var node = doc.CreateElement("root");
    node.InnerXml = escaped;
    return node.InnerText;
}
Darin Dimitrov
Cool, darin! I like your answer.
George2
You don't even need to append the element to the document. However, I'd still say that it's best not to try to do this in the first place - it sounds like George is making work for himself by doing things by hand...
Jon Skeet
Completely agree with you Jon. I didn't know that it wasn't necessary to append the node to make it work. That's why I love StackOverflow - I learn so many things every day.
Darin Dimitrov
I really dislike this answer because it's too heavy-weight. XmlDocument is going to use XmlReader/XmlWriter to do the real work, so why not cut to the chase and avoid that heavy DOM?
Steven Sudit
This answer also doesn't escape quotes. Fail.
Will
@Will, simple quotes don't need to be escaped like double quotes. What this sample guarantees is that it will generate valid XML no matter what you put in the string.
Darin Dimitrov
@darin I usually say "single quote" and "quote", I guess you say "quote" and "double quote." I did mean, as you say, "double quotes" as your escape method does not escape "double quotes", so your function does not correctly escape text for use in an XML document. The use of the SecurityElement to escape text and your unescape method works well enough, however. So you're half right.
Will
@Will, the OP asked for a function that will escape a text which could be put in a XML **element** and not attribute. My function doesn't escape single or double quotes because they can be put in XML elements.
Darin Dimitrov
@darin good point, and one that should be stressed. I am satisfied with the result of this conversation, and withdraw my reservations. Good day, sir.
Will
+5  A: 

George, it's simple. Always use the XML APIs to handle XML. They do all the escaping and unescaping for you.

Never create XML by appending strings.

John Saunders
Words to live by. There are many XML API options available, but the one thing we should all agree on is that manual string concatenation is not acceptable.
Steven Sudit
+9  A: 

SecurityElement.Escape(string s)

Dana Holt
+1 Most relevant answer to the question (proper approaches aside).
Mike Atlas
This answer escapes quotes, unlike the selected answer.
Will