使用属性旁边的数据在Java中解析XML

Use*_*920 0 java xml parsing openstreetmap

我需要在Java中获取某些XML对象的值,但它们位于属性标记中.我不知道该如何解决这个问题.

XML示例:

<node id="359832" version="5" timestamp="2008-05-20T15:20:46Z" uid="4499" changeset="486842" lat="50.9051565" lon="6.963755">
    <tag k="amenity" v="restaurant"/>
    <tag k="name" v="Campus"/>
  </node>
  <node id="451153" version="4" timestamp="2009-09-17T18:09:14Z" uid="508" changeset="2514480" lat="51.6020306" lon="-0.1935029">
    <tag k="amenity" v="restaurant"/>
    <tag k="created_by" v="JOSM"/>
    <tag k="name" v="Sun and Sea"/>
  </node>
Run Code Online (Sandbox Code Playgroud)

我需要得到的价值latlon,这是内部<node>除了价值<tag k="name" v="Sun and Sea"/>,并与每个组的这个,用它做什么.

伪代码:

foreach(node in xmlFile)
{
String name = this.name;
double lat = this.lat;
double lon = this.lon;
//my own thing here
}
Run Code Online (Sandbox Code Playgroud)

我看过,但我无法找到如何获取值的东西latlon,因为他们是旁边的属性而不是嵌套.我不需要使用输入流,xml文件足够小,我不能将其存储在内存中.

Dan*_*lan 5

package com.sandbox;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;

public class Sandbox {

    public static void main(String argv[]) throws IOException, SAXException, ParserConfigurationException {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = documentBuilder.parse(Sandbox.class.getResourceAsStream("/foo.xml"));

        NodeList nodeNodeList = document.getElementsByTagName("node");

        for (int i = 0; i < nodeNodeList.getLength(); i++) {

            Node nNode = nodeNodeList.item(i);

            System.out.println(nNode.getAttributes().getNamedItem("lat").getNodeValue());
            System.out.println(nNode.getAttributes().getNamedItem("lon").getNodeValue());

        }

    }


}
Run Code Online (Sandbox Code Playgroud)

打印出来的:

50.9051565
6.963755
51.6020306
-0.1935029
Run Code Online (Sandbox Code Playgroud)