使用Google Geocode在Java中使用XPath解析XML

时间:2013-09-30 18:15:21

标签: java xml google-maps xpath

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

有人能发现错误吗?

1 个答案:

答案 0 :(得分:1)

变化:

xpath.compile("/GeocodeResponse/result/bounds/southwest/lat")

要:

xpath.compile("/GeocodeResponse/result/geometry/bounds/southwest/lat")