kohaNimi = "Tallinn";
URL myUrl = new URL("http://maps.googleapis.com/maps/api/geocode/xml?address=" + kohaNimi + "&sensor=false");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(myUrl.openStream());
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile("/GeocodeResponse/result/bounds/southwest/lat");
String swLat = expr.evaluate(doc, XPathConstants.STRING).toString();
System.out.println("swLat: " + swLat );
所以我尝试使用 Google 地理编码 API 来获取城镇的坐标,但我在解析 xml 时遇到问题。我正在尝试将 xPath 与 Java 一起使用。我可以证实……确实存在。问题是,当我尝试解析此 xml 时,我不会收到任何文本作为响应。我查看了代码,似乎无法找出问题所在。我使用这篇博文来汇编我的代码:http://tunatore.wordpress.com/2011/05/20/how-to-use-xpath-i-java-simple-example/
您可以从这里验证 xpath 是否正确(应该得到响应):http://maps.googleapis.com/maps/api/geocode/xml?address=Tallinn&sensor=false
谁能发现问题所在吗?
最佳答案
更改:
xpath.compile("/GeocodeResponse/result/bounds/southwest/lat")
致:
xpath.compile("/GeocodeResponse/result/geometry/bounds/southwest/lat")
关于java - 使用 Google Geocode 在 Java 中使用 XPath 解析 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19100973/