简体   繁体   中英

Get all information for a node from XML file with java

I have a school project to read an osm file and create a database. So now, I need to extract the latitude, longitude, and the name of all restaurants from the file. Here's my code and a part of the osm file. I need to know how to extract the wanted values. Thank you!

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(map);
        
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile("//node[@lat>0]");
NodeList nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
        
for(int i=0; i<nl.getLength(); i++) {
    System.out.println(nl.item(i).getNodeName()); //returns "node"
}

OSM File:

<node id="6814246387" visible="true" version="1" changeset="74752372" timestamp="2019-09-21T15:31:14Z" user="YunDi88" uid="9047835" lat="42.0015821" lon="21.4189761">
  <tag k="amenity" v="restaurant"/>
  <tag k="name" v="Restaurant"/>
 </node>
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(map);
        
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile("//node[@lat>0]");
NodeList nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
        
for(int i=0; i<nl.getLength(); i++) {
    Node currentItem=nl.item(i);
    String value=currentItem.getAttributes().getNamedItem("lat").getNodeValue();
    System.out.println(value);
}

This should work. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM