内置.NET函数,用于在XML流中转义字符?

所以,我有一些以下forms的数据:

<foo><bar>test</bar></foo> 

我希望使用哪些.NET类/函数将其转换为漂亮的东西,然后将其写入文件,如下所示:

   test   

具体说明函数和类,而不仅仅是“使用System.XML”。 使用XML在.NET中似乎有很多不同的方法:(

谢谢

使用System.Xml.XmlDocument类…

 Dim Val As String = "<foo><bar>test</bar></foo>" Dim Xml As String = HttpUtility.HtmlDecode(Val) Dim Doc As New XmlDocument() Doc.LoadXml(Xml) Dim Writer As New StringWriter() Doc.Save(Writer) Console.Write(Writer.ToString()) 

你可以使用这段代码。

 string p = "<foo><bar>test</bar></foo>"; Console.WriteLine(System.Web.HttpUtility.HtmlDecode(p)); 

如果漂亮打印不重要,请使用自.NET 4.0以来的System.Net.WebUtility.HtmlDecode 。

这是我使用的一个,传入Xml字符串,如果要将包含“ ”的字符串转换为本机xml等效字符串,将ToXml设置为true,“#lt; foo / #gt;# LT;棒#gt;”中 – 用&ampersand替换散列,因为这个编辑器一直在逃避它…同样,如果ToXml为false,它将转换一个包含“#lt; foo / #gt; #lt; bar #gt;”的字符串。 ( 用和号替换哈希 )到“

 string XmlConvert(string sXml,bool ToXml){
     string sConvertd = string.Empty;
     if(ToXml){
        sConvertd = sXml.Replace(“<”,“#lt;”)。替换(“>”,“#gt;”)。替换(“&”,“#amp;”);
     }其他{
        sConvertd = sXml.Replace(“#lt;”,“<”)。替换(“#gt;”,“>”)。替换(“#amp;”,“&”);
     }
     return sConvertd;
 }

用&ampersand替换哈希值,因为这个编辑器会在pre标签中转义它)

编辑:感谢technophile指出显而易见的,但这只是为了涵盖XML标签。 这是该function的要点,可以很容易地扩展到其他XML标签,并随意添加我可能错过的更多! 干杯! 🙂