使用 java 从 XML 文件获取节点的所有信息

Get all information for a node from XML file with java

我有一个学校项目要读取 osm 文件并创建数据库。所以现在,我需要从文件中提取纬度、经度和所有餐馆的名称。这是我的代码和 osm 文件的一部分。我需要知道如何提取想要的值。谢谢!

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 文件:

<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);
}

这应该有效。 :)