【问题标题】:How to handle with org.xml.sax.SAXParseException? [duplicate]如何处理 org.xml.sax.SAXParseException? [复制]
【发布时间】:2019-07-17 01:29:52
【问题描述】:

A 试图从 https://www.boardgamegeek.com/xmlapi/boardgame/13/catan 解析 XML 并获取 Language Dependence 的最高 numvotes 的值。

这是代码:

public class DomParserDemo {

    public static void main(String[] args) {

        try {

            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dbBuilder = dbFactory.newDocumentBuilder();
            InputSource is = new InputSource(new StringReader("please paste XML from link");
                    Document doc = dbBuilder.parse(is);
            doc.getDocumentElement().normalize();
            System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
            NodeList nodeList = doc.getElementsByTagName("result") ;

            String targetValue = "";
            int maxNumVotes = 0;
            for (int i = 0; i < nodeList.getLength(); i++) {
                Element element = (Element) nodeList.item(i);
                int numVotes = Integer.parseInt(element.getAttribute("numvotes"));
                if (numVotes > maxNumVotes) {
                    maxNumVotes = numVotes;
                    targetValue = element.getAttribute("value");
                }
            }
            System.out.println("Value: " + targetValue + " NumVotes: " + maxNumVotes);

        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
} 

输出:

[Fatal Error] :1:10703: The entity name must immediately follow the '&' in the entity reference.
org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 10703; The entity name must immediately follow the '&' in the entity reference.
    at java.xml/com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:261)
    at java.xml/com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:339)
    at DomParserDemo.main(DomParserDemo.java:17)

【问题讨论】:

    标签: java xml jdom parsexml


    【解决方案1】:

    如果你在浏览器中打开网址并搜索&amp;amp;,第一次点击会找到:

    BGTG 115 - Spiel des Jahres, Then &amp;amp; Now

    &amp;amp; 是一个有效的实体引用。

    如果继续搜索,第二次点击填充查找:

    Catan: Cities &amp; Knights

    这是无效的 XML。 &amp;amp; 后面必须跟一个名称和一个;。要在值中包含&amp;amp;,必须将其转义为&amp;amp;

    简而言之,该 URL 返回的 XML 无效,Java XML 解析器会告诉您。

    【讨论】:

    • 您有什么解决方案吗?
    • 解决方案是修复您的 XML。目前您正在尝试解析不是格式良好的 XML 的内容,因此 XML 解析器是无用的。
    猜你喜欢
    • 2015-03-09
    • 2013-12-08
    • 2017-12-24
    • 2013-03-29
    • 2016-07-28
    • 2022-01-23
    • 2019-01-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多