Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 628
George2 Avatar asked Jul 15 '09 16:07

George2


People also ask

How do I escape a string in XML?

XML escape characters There are only five: " &quot; ' &apos; < &lt; > &gt; & &amp; Escaping characters depends on where the special character is used. The examples can be validated at the W3C Markup Validation Service.

How do you escape a colon in XML?

Colon is a reserved character in XML identifiers, and may be used only for binding XML Namespaces. There is no way to escape it for other purposes.


2 Answers

SecurityElement.Escape(string s)

like image 98
TWA Avatar answered Oct 16 '22 11:10

TWA


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; } 
like image 33
Darin Dimitrov Avatar answered Oct 16 '22 10:10

Darin Dimitrov