Reference to undeclared entity exception while working with XML

戏子无情 提交于 2019-11-27 14:36:57

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.

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.

Try replacing &Alpha with

  &#913;

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">

You could also set the InnerText to "Hello, I am text α – —", making the XmlDocument escape them automatically. I think.

The use of a HtmlDocument wasn't suitable in my situation, our system had a custom XmlUrlResolver which we made use of for loading the xml.

//setup
public class CustomXmlResolver : XmlUrlResolver { /* ... */ }
String originalXml; //fetched xml with html entities in it

var doc = new XmlDocument();
doc.XmlResolver = new AdCastXmlResolver();

//making use of a transitional dtd
doc.LoadXml("<!DOCTYPE html SYSTEM \"xhtml1-transitional.dtd\" > " + originalXml);

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

If you do want to use the HTML entity names you are used to, the W3C has got you covered and has produced "XML Entity Definitions for Characters" http://www.w3.org/TR/xml-entity-names/, which essentially is a list of named entities very similar to the ones that HTML has. But as mentioned above, this is not built into XML, and needs to be explicitly supported by XML applications that want to use these named entities.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!