xml通配符

来源:互联网 发布:淘宝专业差评 编辑:程序博客网 时间:2024/05/21 03:57
文章来源:http://pay.iteye.com/blog/1721491



解析xml字符串 
< -> &lt; 
> -> &gt; 
" -> &quot; 
' -> &apos; 
& -> &amp; 

1. 利用string.Replace() 五次替换 

string xml = "<node>it's my \"node\" & i like it<node>"; 
encodedXml = xml.Replace("&", "&amp;").Replace("<", "&lt;").Replace(">", "&gt;").Replace("\"", "&quot;").Replace("'", "&apos;"); 
// RESULT: &lt;node&gt;it&apos;s my &quot;node&quot; &amp; i like it&lt;node&gt; 



2. 利用System.Web.HttpUtility.HtmlEncode() 方便 

string xml = "<node>it's my \"node\" & i like it<node>"; 
string encodedXml = HttpUtility.HtmlEncode(xml); 
// RESULT: &lt;node&gt;it's my &quot;node&quot; &amp; i like it&lt;node&gt; 

3. 利用System.Security.SecurityElement.Escape() 不常用 

string xml = "<node>it's my \"node\" & i like it<node>"; 
string encodedXml = System.Security.SecurityElement.Escape(xml); 
// RESULT: &lt;node&gt;it&apos;s my &quot;node&quot; &amp; i like it&lt;node&gt 


4. 利用 System.Xml.XmlTextWriter 

string xml = "<node>it's my \"node\" & i like it<node>"; 
using (XmlTextWriter xtw = new XmlTextWriter(@"c:\xmlTest.xml", Encoding.Unicode)) 

xtw.WriteStartElement("xmlEncodeTest"); 
xtw.WriteAttributeString("testAttribute", xml); 
xtw.WriteString(xml); 
xtw.WriteEndElement(); 

// RESULT: 
/* 
<xmlEncodeTest testAttribute="&lt;node&gt;it's my &quot;node&quot; &amp; i like it&lt;node&gt;"> 
&lt;node&gt;it's my "node" &amp; i like it&lt;node&gt; 
</xmlEncodeTest> 
*/

0 0