Reputation: 3253
I need to get the value of certain XML objects in Java, but they are in the attribute tag. I'm not sure how to go about this.
XML Example:
<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>
I need to get the value of lat
and lon
, which are inside of the <node>
in addition to the value of <tag k="name" v="Sun and Sea"/>
, and with each set of this, do something with it.
Pseudocode:
foreach(node in xmlFile)
{
String name = this.name;
double lat = this.lat;
double lon = this.lon;
//my own thing here
}
I have looked, but am unable to find anything on how to get the values for lat
and lon
, since they are next to the attribute instead of nested. I don't need to use an input-stream, the xml file is small enough that I cant store it in memory.
Upvotes: 0
Views: 265
Reputation: 67390
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());
}
}
}
This printed out:
50.9051565
6.963755
51.6020306
-0.1935029
Upvotes: 5