How to decode string to XML string in C#

后端 未结 7 1509
挽巷
挽巷 2020-11-27 20:41

I have a string (from a CDATA element) that contains description of XML. I need to decode this string into a new string that displays the characters correctly using C#

相关标签:
7条回答
  • 2020-11-27 21:30

    As Kirill and msarchet said, you can use HttpUtility.HtmlDecode from System.Web. It escapes pretty much anything correctly.

    If you don't want to reference System.Web you might use some trick which supports all XML escaping but not HTML-specific escaping like é:

    public static string XmlDecode(string value) {
        var xmlDoc = new XmlDocument();
        xmlDoc.LoadXml("<root>" + value + "</root>");
        return xmlDoc.InnerText;
    }
    

    You could also use a RegEx or simple string.Replace but it would only support basic XML escaping. Things like &#x410; or &eacute; are examples that would be harder to support.

    0 讨论(0)
提交回复
热议问题