最近在解析谷歌地图的kmz文件,终于弄好了,做个备忘!
准备:kmz文件可以从点击打开链接这里获取,点击红色kml,既可下载kmz文件。
事先下载好了sh1318.kmz文件
1、依赖
<dependency>
<groupId>jaxen</groupId>
<artifactId>jaxen</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
2、解压kmz文件成kml
public Document unzipKmzToKmal() throws Exception, Exception {
File file = new File("sh1318.kmz");
ZipFile zipFile = new ZipFile(file);
ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(file));
InputStream inputStream = null;
ZipEntry entry = null;
Document doc = null;
while ((entry = zipInputStream.getNextEntry()) != null) {
String zipEntryName = entry.getName();
//获取所需文件的节点
if (zipEntryName.equals("doc.kml")) {
inputStream = zipFile.getInputStream(entry);
SAXReader reader = new SAXReader();
doc = reader.read(inputStream);
inputStream.close();
}
}
zipFile.close();
zipInputStream.close();
return doc;
}
解析出来的kml文件如下图:
3、使用selectNodes标签获取指定节点工具。刚开始直接使用selectNodes,一
直返回list是空,最后发现是命名空间问题。
自己写一个获取数据方法,将指定节点的字符串传入list集合中,Qname是标签的名称,可以是多个;document是步骤2中返回的
public List<String> getNodesTextByQName(String[] QName, Document document) {
List<String> list = new ArrayList<String>();
Map<String, String> map = new HashMap<String, String>();
String nameSpaceUrI = document.getRootElement().getNamespaceURI();
map.put("nameSpaceUrI", nameSpaceUrI);
String xpathExpression = "";
for (String s : QName) {
xpathExpression = "//nameSpaceUrI:" + s;
}
XPath xPath = document.createXPath(xpathExpression);
xPath.setNamespaceURIs(map);
List<Node> list1 = xPath.selectNodes(document);
for (Node node : list1) {
list.add(node.getText());
// log.info(node.getText());
}
return list;
}
例如:我要获取<LookAt>节点下<range>标签中数值,遍历list即可获取range中的值。
List<String> list = getNodesTextByQName(new String[]{"LookAt","range"},document);
再长的路,一步步也能走完,再短的路,不迈开双脚也无法到达!