这是使用Java解析kml文件的工具类,会遍历打印出kml所有的节点和值,并不会只解析点线面的节点 好用的话点个赞👍
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class ReadKml {
public static void main(String[] args) throws Exception {
File file = new File("E:/寺庙河航线.kml");
InputStream in = new FileInputStream(file);
parseXmlWithDom4j(in);
}
/**
* 这个是kml的压缩包,如果直接是kml文件就不需要调用这个方法了
**/
public static void parseKml() throws Exception
{
File file = new File("压缩文件地址");//pathName压缩包文件,解压后会有一个kml文件
try {
ZipFile zipFile = new ZipFile(file);
ZipInputStream zipInputStream = null;
InputStream inputStream = null;
ZipEntry entry = null;
zipInputStream = new ZipInputStream(new FileInputStream(file));
while ((entry = zipInputStream.getNextEntry()) != null) {
String zipEntryName = entry.getName();
System.out.println("压缩实体的名称:"+ zipEntryName);
if (zipEntryName.endsWith("kml") || zipEntryName.endsWith("kmz")) {
inputStream = zipFile.getInputStream(entry);
parseXmlWithDom4j(inputStream);
}else if (zipEntryName.endsWith("png")) {
/*ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
byte[] b = new byte[512];
int readedByteSize = 0;
while ((readedByteSize = zipInputStream.read(b)) != -1) {
byteArrayOut.write(b, 0, readedByteSize);
}
byteArrayOut.flush();
byteArrayOut.close();
InputStream isBitmap = new ByteArrayInputStream(byteArrayOut.toByteArray());
Bitmap bitmap = BitmapFactory.decodeStream(isBitmap);
isBitmap.close();*/
}
}
zipInputStream.close();
inputStream.close();
} catch (ZipException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void parseXmlWithDom4j(InputStream input) throws Exception
{
SAXReader reader = new SAXReader();
Document document = null;
try {
document = reader.read(input);
} catch (DocumentException e) {
e.printStackTrace();
}
Element root = document.getRootElement();//获取kml文件的根结点
listNodes(root);
}
//遍历当前节点下的全部节点
public static void listNodes(Element node){
System.out.println("当前结点的名称:"+ node.getName()+"当前节点的值"+node.getTextTrim());
//首先获取当前节点的全部属性节点
/* List<Attribute> list = node.attributes();
//遍历属性节点
for(Attribute attribute : list){
System.out.println("属性"+attribute.getName() +":" + attribute.getValue());
} */
//假设当前节点内容不为空,则输出
if(!(node.getTextTrim().equals("")) && "description".equals(node.getName())){
System.out.println("当前结点内容:"+node.getText());
}
//同一时候迭代当前节点以下的全部子节点
//使用递归
Iterator<Element> iterator = node.elementIterator();
while(iterator.hasNext()){
Element e = iterator.next();
listNodes(e);
}
}
}