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

时间:2014-01-28 01:03:20

标签: 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>

我需要获得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
}

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

1 个答案:

答案 0 :(得分: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());

        }

    }


}

打印出来:

50.9051565
6.963755
51.6020306
-0.1935029