Reference to undeclared entity exception while working with XML

31,647

Solution 1

XML, unlike HTML does not define entities (ie named references to UNICODE characters) so α — etc. are not translated to their corresponding character. You must use the numerical value instead. You can only use < and & in XML

If you want to create HTML, use an HtmlDocument instead.

Solution 2

In .Net, you can use the System.Xml.XmlConvert class:

string text = XmlConvert.EncodeName("Hello α");

Alternatively, you can declare the entities locally by putting the declarations between square brackets in a DOCTYPE declaration. Add the following header to your xml:

<!DOCTYPE documentElement[
<!ENTITY Alpha "&#913;">
<!ENTITY ndash "&#8211;">
<!ENTITY mdash "&#8212;">
]>

Do a google on "html character entities" for the entity definitions.

Solution 3

Try replacing &Alpha with

  &#913;

Solution 4

The preceding answer is right. Another alternative is to link your html document to the DTD where those character entities are defined, and that is standard XHTML DTD definition. Your xml file should include the following declaration:

 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
            "http://www.w3.org/TR/html4/strict.dtd">

Solution 5

Use string System.Net.WebUtility.HtmlDecode(string) which will decode all HTML entity encoded characters to its Unicode variant. It is available from dot.net framework 4

Share:
31,647
Rob
Author by

Rob

Updated on July 29, 2022

Comments

  • Rob
    Rob over 1 year

    I am trying to set the innerxml of a xmldoc but get the exception: Reference to undeclared entity

    XmlDocument xmldoc = new XmlDocument();
    string text = "Hello, I am text &alpha; &nbsp; &ndash; &mdash;"
    xmldoc.InnerXml = "<p>" + text + "</p>";
    

    This throws the exception:

    Reference to undeclared entity 'alpha'. Line 2, position 2..

    How would I go about solving this problem?