Built in .NET function for unescaping characters in XML stream?

后端 未结 4 1968
無奈伤痛
無奈伤痛 2020-12-20 12:06

So, I have some data in the form of:

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

What .NET classes/f

相关标签:
4条回答
  • 2020-12-20 12:48

    Using the System.Xml.XmlDocument class...

    Dim Val As String = "&lt;foo&gt;&lt;bar&gt;test&lt;/bar&gt;&lt;/foo&gt;"
    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())
    
    0 讨论(0)
  • 2020-12-20 12:52

    Use System.Net.WebUtility.HtmlDecode since .NET 4.0 if pretty printing is not important.

    0 讨论(0)
  • 2020-12-20 12:57

    Here's one that I use, pass in an Xml string, set ToXml to true if you want to convert a string containing "<foo/><bar/>" to the native xml equivalent, "#lt;foo/#gt;#lt;bar#gt;" - replace the hash with the ampersand as this editor keeps escaping it...likewise, if ToXml is false, it will convert a string containing the "#lt;foo/#gt;#lt;bar#gt;" (replace the hash with the ampersand)to "<foo/><bar/>"

    string XmlConvert(string sXml, bool ToXml){
        string sConvertd = string.Empty;
        if (ToXml){
           sConvertd = sXml.Replace("<", "#lt;").Replace(">", "#gt;").Replace("&", "#amp;");
        }else{
           sConvertd = sXml.Replace("#lt;", "<").Replace("#gt;", ">").Replace("#amp;", "&");
        }
        return sConvertd;
    }
    

    (replace the hash with the ampersand as this editor keeps escaping it within the pre tags)

    Edit: Thanks to technophile for pointing out the obvious, but that is designed to cover only the XML tags. That's the gist of the function, which can be easily extended to cover other XML tags and feel free to add more that I may have missed out! Cheers! :)

    0 讨论(0)
  • 2020-12-20 13:08

    you can use this code.

    string p = "&lt;foo&gt;&lt;bar&gt;test&lt;/bar&gt;&lt;/foo&gt;";
    Console.WriteLine(System.Web.HttpUtility.HtmlDecode(p));
    
    0 讨论(0)
提交回复
热议问题