Java XML处理实体问题?

当我尝试运行我的java程序时,我得到以下错误(它应该读取一个xml文件并打印出一些内容)。

根据我的理解,有一个未引用的实体,它不是xml标准的一部分,所以我的问题是; 我该如何解决这个问题?

谢谢,

[Fatal Error] subject.xml:4:233: The entity "rsquo" was referenced, but not declared. org.xml.sax.SAXParseException: The entity "rsquo" was referenced, but not declared. at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(Unknown Source) at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(Unknown Source) at javax.xml.parsers.DocumentBuilder.parse(Unknown Source) at DomParserExample2.parseXmlFile(DomParserExample2.java:42) at DomParserExample2.runExample(DomParserExample2.java:24) at DomParserExample2.main(DomParserExample2.java:115) Exception in thread "main" java.lang.NullPointerException at DomParserExample2.parseDocument(DomParserExample2.java:54) at DomParserExample2.runExample(DomParserExample2.java:27) at DomParserExample2.main(DomParserExample2.java:115) 

实体 不是XML实体。 它在HTML中定义: http : //en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references

如果您创建了XML,则可以向DTD添加实体。

像这样的东西可以帮助: http : //gv.ca/dtd/character-entities.dtd

编辑:要解决此问题,您可以将DTD添加到XML文件(如果尚未定义)。

你的XML:

    

你的DTD:

   

如果您向应用程序提供DTD,则错误消失。 我不会写自己的Entites,我会使用W3C中的一个http://www.w3.org/TR/xhtml1/DTD/xhtml-lat1.ent

如何为您的XML包含DTD是另一个问题。 据我所知,您可以设置DTD或目录文件的路径。

编辑2:看一下EntityResolver: http : //download.oracle.com/javase/1.4.2/docs/api/org/xml/sax/EntityResolver.html

根据Christian的回答,您还可以将您的实体声明为XML

   ]> 
 /** * This Inner class is written to solve the XML parsing DTD validation * checking from online because if Internet is not connected, then it * throws Exception. * * @author Ravi Thapa */ public class CustomEntityResolver implements EntityResolver { public InputSource resolveEntity(String publicId, String systemId) { InputSource source = null; Pattern pattern1 = Pattern.compile("^-//(.*)//DTD(.*)$", Pattern.CASE_INSENSITIVE); Matcher match1 = pattern1.matcher(publicId.trim()); Pattern pattern2 = Pattern.compile("^http://(.*).dtd$", Pattern.CASE_INSENSITIVE); Matcher match2 = pattern2.matcher(systemId.trim()); if (match1.find() || match2.find()) { source = new InputSource(new ByteArrayInputStream("".getBytes())); } // return null to signal default behavior return source; } }