String escape into XML

xml escape backslash
xml escape characters c#
xml escape slash
escape xml java
xml escape ampersand
xml cdata escape
xml encode
xml escape generator

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.

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

Free Online XML Escape / Unescape Tool, If you use an appropriate class or library, they will do the escaping for you. Many XML issues are caused by string concatenation. XML escape  I had a look at string escape into XML and found it very useful. I would like to do a similar thing: Escape a string to be used in an XML-Attribute. The string may contain \r . The XmlWriter class produces something like \r -> &#xD;&#xA; The solution I'm currently using includes the XmlWriter and a StringBuilder and is rather ugly. Any hints

SecurityElement.Escape(string s)

What characters do I need to escape in XML documents?, XML escaped characters. XML special characters get escaped at install time as follows: Special character, escaped form, gets replaced by  XML Escape / Unescape. Escapes or unescapes an XML file removing traces of offending characters that could be wrongfully interpreted as markup. The following characters are reserved in XML and must be replaced with their corresponding XML entities: ' is replaced with &apos; " is replaced with &quot; & is replaced with &amp; < is replaced with &lt;

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.

XML escaped characters, These are the characters which are used to markup XML syntax; when they In addition, the string “–” must not appear within comments. re: Different ways how to escape an XML string in C# Another way is simply to use the InnerText and InnerXml properties of an XmlDOM node. string xml = "<node>it's my \"node\" & i like it<node>";

Thanks to @sehe for the one-line escape:

var escaped = new System.Xml.Linq.XText(unescaped).ToString();

I add to it the one-line un-escape:

var unescapedAgain = System.Xml.XmlReader.Create(new StringReader("<r>" + escaped + "</r>")).ReadElementString();

Best Online Tool to XML Escape Unescape, When you use wizards to customize any string in your XML file, you can use the Instead, use the following escape sequences to represent these symbols. Escaping XML Data Adding control characters ('<', '>', ''', '"', '&') into xml data can cause the parser to miss understand the resulting data. The solution is to escape the control characters so that the parser can interpret them correctly as data, and not confuse them for markup.

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.

What Characters Need to be Escaped in XML Documents?, You need to escape specific XML characters in Liberty configuration files, such as the server.xml file because Liberty does not automatically escape these  XML Escape Escapes or unescapes an XML file removing traces of offending characters that could be wrongfully interpreted as markup. ' is replaced with ', " is replaced with ", & is replaced with &, is replaced with <, > is replaced with >.

Using Special Characters in XML, The invalid characters are translated into escaped numeric entity encodings. The escape character is "_". Any XML name character that does not conform to the  If you use an appropriate class or library, they will do the escaping for you. Many XML issues are caused by string concatenation. XML escape characters. There are only five:" &quot; ' &apos; < &lt; > &gt; & &amp; Escaping characters depends on where the special character is used.

XML escape characters, xml.sax.saxutils. escape (data[, entities])¶. Escape '&' , '<' , and '>' in a string of data. You can escape other strings of data by passing a dictionary as the optional​  STRING_ESCAPE is a deterministic function, introduced in SQL Server 2016. Transact-SQL Syntax Conventions. Syntax STRING_ESCAPE( text , type ) Arguments. text Is a nvarcharexpression expression representing the object that should be escaped. type Escaping rules that will be applied. Currently the value supported is 'json'. Return Types

XmlConvert.EncodeName(String) Method (System.Xml), 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.

Comments
  • 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
  • Shortest I can think of: new XText(unescaped).ToString()
  • For anyone else stumbling upon this, I've found this to be the best answer: stackoverflow.com/a/5304827/1224069
  • 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...
  • 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?
  • @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 good point, and one that should be stressed. I am satisfied with the result of this conversation, and withdraw my reservations. Good day, sir.
  • I wonder if HttpUtility.HtmlEncode from System.Web could safely be used?
  • This answer escapes quotes, unlike the selected answer.
  • This answer doesn't seem to work with invalid characters like �
  • And how do you un-escape?
  • This answer is incomplete. It only answers half of the question.
  • Agree with above comments - incomplete and not 100% accurate.
  • Thanks Jon, I have put more details into my original post EDIT 1 section. Appreciate if you could give me some comments and advice. :-)