Why does Html decode not working for * $

Viewed 1122

I have a console application to load XmlDocument , but it fail to load if the string has values like * $

Any idea how to load the xml? all responses are appreciated

using System;
using System.Net;   
using System.Xml;

public class Program
{
    public static void Main()
    {
        //string xmlStringWorking = "<xml>&copy; &uml; &Agrave; &yen; &sect;</xml>";

        string xmlStringWorking = "<xml>&ast; &dollar; &copy; &uml; &Agrave; &yen; &sect;</xml>";

        xmlStringWorking= WebUtility.HtmlDecode(xmlStringWorking);

        XmlDocument doc = new XmlDocument();
                        doc.LoadXml(xmlStringWorking);

        Console.WriteLine(xmlStringWorking);
    }
}

expecting special characters are here

dotnetfiddle

4 Answers

HtmlDecode is just intended to undo the effects of HtmlEncode. Since * and $ have no special meaning in HTML, they don't need to be encoded; therefore HtmlEncode would not encode them as &ast; and &dollar;; therefore HtmlDecode will not decode them.

You can replace: * by &#42; $ by &#36;

string xmlStringWorking = "<xml>&#42; &#36; &copy; &uml; &Agrave; &yen; &sect;</xml>";

DotNet 4.7 method WebUtility.HtmlDecode don't support decodeing html5 entity set.

With the help of "AngleSharp" library we are able to parse html5 entities correctly

using System;
using System.Net;   
using System.Xml;
using AngleSharp.Parser.Html;
public class Program
{
    public static void Main()
    {
        string xmlStringWorking = "<xml>&ast; &dollar; &copy; &uml; &Agrave; &yen; &sect;</xml>";

        var parser = new HtmlParser();

        var document = parser.Parse(xmlStringWorking);

        XmlDocument doc = new XmlDocument();

        doc.LoadXml(document.DocumentElement.GetElementsByTagName(@"body").First().InnerHtml.Replace("&nbsp;"," "));

        Console.WriteLine(document.DocumentElement.GetElementsByTagName(@"body").First().InnerHtml.Replace("&nbsp;"," "));
    }
}

But it failed on character &nbsp;

Temporary fix .Replace("&nbsp;"," ") is working.

Related