br.zuq.osm.parser.OSMParser Maven / Gradle / Ivy
package br.zuq.osm.parser;
import br.zuq.osm.parser.model.OSM;
import br.zuq.osm.parser.model.OSMNode;
import br.zuq.osm.parser.model.Relation;
import br.zuq.osm.parser.model.Way;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.InputStream;
import java.util.*;
/**
* @author Willy Tiengo
*/
public class OSMParser {
/**
*
*/
public static OSM parse(InputStream is) throws Exception {
Document doc;
DocumentBuilder builder;
Node node;
NodeList nodesList;
Map nodes = new LinkedHashMap();
builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
doc = builder.parse(is);
nodesList = doc.getChildNodes().item(0).getChildNodes();
OSM osm = new OSM();
for (int i = 0; i < nodesList.getLength(); i++) {
node = nodesList.item(i);
if (NodeParser.isNode(node)) {
OSMNode osmNode = NodeParser.parseNode(node);
nodes.put(osmNode.id, osmNode);
osm.getNodes().add(osmNode);
} else if (WayParser.isWay(node)) {
Way way = WayParser.parseWay(node, nodes);
osm.getWays().add(way);
} else if (RelationParser.isRelation(node)) {
Relation relation = RelationParser.parseRelation(osm, node);
osm.getRelations().add(relation);
}
}
Set nodeset = new HashSet<>();
for (String n : nodes.keySet()) {
nodeset.add(nodes.get(n));
}
return osm;
}
protected static Map parseTags(NodeList nodes) {
Map tags = new HashMap();
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
if (node.getNodeName().equals("tag")) {
addTag(tags, node);
}
}
return tags;
}
private static void addTag(Map tags, Node node) {
String key = node.getAttributes().getNamedItem("k").getNodeValue();
String value = node.getAttributes().getNamedItem("v").getNodeValue();
if (tags.get(key) != null) {
tags.put(key, tags.get(key) + ";" + value);
} else {
tags.put(key, value);
}
}
}