XML string output

Is there any C # function that can be used to delete and delete a string that can be used to populate the contents of an XML element?

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

EDIT 1: I am connecting a simple and short XML file and I am not using serialization, so I need to explicitly escape the XML character manually, for example, I need to put a<b in <foo></foo> , so I need to escape string a<b and put it in the foo element.

+80
c # xml visual-studio-2008 escaping
Jul 15 '09 at 16:30
source share
10 answers
 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; } 
+68
Jul 15 '09 at 16:39
source share
+109
Jul 15 '09 at 17:08
source share

EDIT: you say: "I am concatenating a simple and short XML file and I am not using serialization, so I need to explicitly avoid the XML character manually."

I would strongly advise you not to do this manually. Use the XML API to do all this for you - read in the source files, merge them into one document, but you need to (you probably want to use XmlDocument.ImportNode ) and then write it again. You do not want to write your own XML parsers / formatter. Serialization is somewhat irrelevant here.

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




Original answer

It's not entirely clear what you mean, but usually the XML APIs do this for you. You set the text to node and it automatically avoids everything it needs. 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); } } 

The result of both examples:

 <tag>Brackets &amp; stuff &lt;&gt;</tag> 

This assumes that you want XML escaping, of course. If you do not, write more detailed information.

+33
Jul 15 '09 at 16:35
source share

Thanks to @sehe for a one-line escape code:

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

I add a single-line un-escape to it:

 var unescapedAgain = System.Xml.XmlReader.Create(new StringReader("<r>" + escaped + "</r>")).ReadElementString(); 
+22
Oct 21 '13 at 15:33
source share

George, that’s easy. Always use the XML API to process XML. They do everything possible and accelerating for you.

Never create XML by adding strings.

+9
Jul 15 '09 at 17:04
source share

And if you want, like me, when I found this question, avoid XML node names, for example, when reading from XML serialization, use the simplest way:

 XmlConvert.EncodeName(string nameToEscape) 

It will also avoid spaces and any invalid characters for XML elements.

http://msdn.microsoft.com/en-us/library/system.security.securityelement.escape%28VS.80%29.aspx

+4
Jan 29 '14 at 2:35
source share

WARNING: Necromancers

However, Darin Dimitrov answers + System.Security.SecurityElement.Escape (line s) is not complete.

In XML 1.1, the easiest and safest way is to simply encode EVERYTHING.
Like &#09; for \ t.
It is not supported at all in XML 1.0.

For XML 1.0, one possible workaround is base-64, which encodes text containing character (s).

 //string EncodedXml = SpecialXmlEscape(" "); //Console.WriteLine(EncodedXml); //string DecodedXml = XmlUnescape(EncodedXml); //Console.WriteLine(DecodedXml); public static string SpecialXmlEscape(string input) { //string content = System.Xml.XmlConvert.EncodeName("\t"); //string content = System.Security.SecurityElement.Escape("\t"); //string strDelimiter = System.Web.HttpUtility.HtmlEncode("\t"); // XmlEscape("\t"); //XmlDecode("&#09;"); //strDelimiter = XmlUnescape("&#59;"); //Console.WriteLine(strDelimiter); //Console.WriteLine(string.Format("&#{0};", (int)';')); //Console.WriteLine(System.Text.Encoding.ASCII.HeaderName); //Console.WriteLine(System.Text.Encoding.UTF8.HeaderName); string strXmlText = ""; if (string.IsNullOrEmpty(input)) return input; System.Text.StringBuilder sb = new StringBuilder(); for (int i = 0; i < input.Length; ++i) { sb.AppendFormat("&#{0};", (int)input[i]); } strXmlText = sb.ToString(); sb.Clear(); sb = null; return strXmlText; } // End Function SpecialXmlEscape 

XML 1.0:

 public static string Base64Encode(string plainText) { var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText); return System.Convert.ToBase64String(plainTextBytes); } public static string Base64Decode(string base64EncodedData) { var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData); return System.Text.Encoding.UTF8.GetString(base64EncodedBytes); } 
+3
Apr 09 '14 at 9:44
source share

The following functions will do the job. Did not test XmlDocument, but I think it is much faster.

 public static string XmlEncode(string value) { System.Xml.XmlWriterSettings settings = new System.Xml.XmlWriterSettings { ConformanceLevel = System.Xml.ConformanceLevel.Fragment }; StringBuilder builder = new StringBuilder(); using (var writer = System.Xml.XmlWriter.Create(builder, settings)) { writer.WriteString(value); } return builder.ToString(); } public static string XmlDecode(string xmlEncodedValue) { System.Xml.XmlReaderSettings settings = new System.Xml.XmlReaderSettings { ConformanceLevel = System.Xml.ConformanceLevel.Fragment }; using (var stringReader = new System.IO.StringReader(xmlEncodedValue)) { using (var xmlReader = System.Xml.XmlReader.Create(stringReader, settings)) { xmlReader.Read(); return xmlReader.Value; } } } 
+2
Jun 21 '13 at 15:42
source share

Using a third-party library ( Newtonsoft.Json ) as an alternative:

 public static string XmlEncode(string unescaped) { if (unescaped == null) return null; return JsonConvert.SerializeObject(unescaped); ; } public static string XmlDecode(string escaped) { if (escaped == null) return null; return JsonConvert.DeserializeObject(escaped, typeof(string)).ToString(); } 

Example:

a<b <==> "a&lt;b"

<foo></foo> <==> "foo&gt;&lt;/foo&gt;"

+1
Aug 12 '18 at 15:16
source share

Another answer based on John Skeet's answer does not return tags :

 void Main() { XmlString("Brackets & stuff <> and \"quotes\"").Dump(); } public string XmlString(string text) { return new XElement("t", text).LastNode.ToString(); } 

This only returns the value passed in XML format:

 Brackets &amp; stuff &lt;&gt; and "quotes" 
0
Nov 30 '18 at 23:11
source share



All Articles