Extracting HTML element with Java and XPath

I am trying to extract the latitude and longitude of an address. Here is the coding.

public static void main(String[] args) throws Exception { int responseCode = 0; String api = "http://maps.googleapis.com/maps/api/geocode/xml?address=9%20Edinburgh%20Place,%20Centrall&sensor=false&components=country:HK&language=en"; URL url = new URL(api); HttpURLConnection httpConnection = (HttpURLConnection)url.openConnection(); httpConnection.connect(); responseCode = httpConnection.getResponseCode(); if(responseCode == 200) { DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();; Document document = builder.parse(httpConnection.getInputStream()); XPathFactory xPathfactory = XPathFactory.newInstance(); XPath xpath = xPathfactory.newXPath(); XPathExpression expr = xpath.compile("/GeocodeResponse/status"); String status = (String)expr.evaluate(document, XPathConstants.STRING); if(status.equals("OK")) { expr = xpath.compile("//*[@id=\"collapsible6\"]/div[1]/div[2]/div[1]/span[2]"); Object results = expr.evaluate(document, XPathConstants.NODESET); NodeList nodes = (NodeList) results; System.out.println(nodes.getLength()); for (int i = 0; i < nodes.getLength(); i++){ System.out.println("latitude: " + nodes.item(i).getNodeValue()); } expr = xpath.compile("//geometry/location/lng"); String lng = (String)expr.evaluate(document, XPathConstants.STRING); System.out.println("longitude: " + lng); } else throw new Exception("Error from the API - response status: "+status); } }}

I have copied the xpath by inspecting the web element and tried to implement it for latitude but it keeps giving me 0 for nodes.getLength(); however, it works well for longitude. If I want to keep the HTML element and make use of it with XPath, how should the code change?

-------------Problems Reply------------

It looks like there is an error in your code on this line:

expr = xpath.compile("//*[@id=\"collapsible6\"]/div[1]/div[2]/div[1]/span[2]");

Shouldn't it be this?

expr = xpath.compile("//geometry/location/lat");

Category:java Views:2 Time:2019-03-07

Related post

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.117 (s). 11 q(s)