2014-01-28 61 views
0

我需要獲取Java中某些XML對象的值,但它們位於屬性標記中。我不知道如何去做這件事。使用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文件足夠小,我不能將它存儲在內存中。

+0

你使用的是什麼解析庫? –

+0

我想用DOM做,但我似乎無法弄清楚如何做到這一點。 – User093203920

回答

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