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 );
所以我试图使用谷歌地理编码 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
谁能发现哪里出了问题?