A 尝试从 https://www.boardgamegeek.com/xmlapi/boardgame/13/catan 解析 XML并获得语言依赖性最高票数的值。
这是代码:
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)
最佳答案
如果您在浏览器中打开 URL 并搜索 &
,第一个命中将找到:
BGTG 115 - Spiel des Jahres,然后和;现在
该 &
是有效的实体引用。
如果继续搜索,第二次点击填充找到:
卡坦岛:城市与骑士
这是无效的 XML。 &
后面必须跟有名称和 ;
。要在值中包含 &
,必须将其转义为 &
。
简而言之,该 URL 返回的 XML 是无效,Java XML 解析器会告诉您这一点。
关于java - 如何处理org.xml.sax.SAXParseException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57067362/