开发者

Is there any built-in function in NET Framework which encodes a string to a valid XML unicode?

开发者 https://www.devze.com 2023-01-16 02:21 出处:网络
After checking an Xps file i noticed that the string within the Xps file <> is converted to &lt;&gt;

After checking an Xps file i noticed that the string within the Xps file <> is converted to &lt;&gt;

So is there any built-in function in the .Net framework that could do this job for me? If it does not exist what characters becides <> should i escape in myOwn function?

I try to开发者_开发知识库 implement a search within an xps file, but searching for <> instead of &lt;&gt; returns nothing.

UPDATE: At least i found the list here of xml document escape characters


XMLTextWriter is what you're looking for. You should avoid using any of the HTMLEncode methods (there are several) unless you're actually encoding your text for use in an HTML document. If you're encoding text for use in an XML document (including XHTML), you should use XMLTextWriter.

Something like this should do the trick:

StringWriter strWriter = new StringWriter();
XmlTextWriter xmlWriter = new XmlTextWriter(strWriter);
xmlWriter.WriteString('Your String Goes here, < and >, as well as other special chars will be properly encoded');
xmlWriter.Flush();

Console.WriteLine("XML Text: {0}", strWriter.ToString());

See also this other stackoverflow discussion.


HtmlEncode should work for you.
&lt; and &gt; is NOT unicode. They're just escaped HTML/XML characters.

Edit:
Come to think of it you could roll your own XmlEncode method since there are only 5 predefined entities in XML. In HTML there are 252.


Not built in but Microsoft have released an anti-cross site scripting library that should help. It adds new features beyond .NET's Html.Encode method, including an XML encoding method.

Tutorial

Download

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号