簡體   English   中英

Java XML處理實體問題?

[英]Java XML processing entity problem?

當我嘗試運行我的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:

<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE demo SYSTEM "./demo.dtd">
<demo>
    &rsquo;
</demo>

你的DTD:

<!ELEMENT demo (#PCDATA)>
<!ENTITY rsquo   "&#8217;">

如果您向應用程序提供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

<!DOCTYPE your_type [
   <!ENTITY rsquo "&#8217;">
   <!ENTITY lsquo "&#8216;">
]>
/**
         * 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;
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM