Extracting HTML element with Java and XPath -
i trying extract latitude , longitude of address. here 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()); (int = 0; < 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 api - response status: "+status); } }}
i have copied xpath inspecting web element , tried implement latitude keeps giving me 0 nodes.getlength(); however, works longitude. if want keep html element , make use of xpath, how should code change?
it looks there error in code on line:
expr = xpath.compile("//*[@id=\"collapsible6\"]/div[1]/div[2]/div[1]/span[2]");
shouldn't this?
expr = xpath.compile("//geometry/location/lat");
Comments
Post a Comment