java 解压Kmz文件selectNodes获取指定标签内容

最近在解析谷歌地图的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);             


再长的路,一步步也能走完,再短的路,不迈开双脚也无法到达!
  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值