(Java)使用 XPath 解析 google 方向 XML 时出错

(Java) Error parsing google directions XML using XPath

我正在尝试使用 google 方向 api 获取两个位置之间的行车路线 api。

我尝试解析使用不同方法返回的 XML,但我总是收到以下错误。

javax.xml.xpath.XPathExpressionException: org.xml.sax.SAXParseException;行号:1;列数:1;序言中不允许包含内容。

//代码已编辑

现在我们已经确定这确实是唯一的问题,我将其添加为答案。

您请求的页面不是XML,而是JSON。 SAX 解析器 returns 错误,因为解析器输入不是格式正确的 XML 文档。它不一定是,因为它是有效的 JSON.

根据@geert3 的建议,只需将 URL 中的 json 替换为 xml:

http://maps.googleapis.com/maps/api/directions/xml?sensor=false&origin=nottingham&destination=derby

否则,parse JSON with a JSON parser and use JSONPath 而不是 XPath 来查询它。