KML服务有两种,一种是纯文本的XML,一种是将一个纯文本的XML文件和其他资源(如图标)进行zip压缩后形成的KMZ,本质是zip。使用Android解析KML服务需要根据情况首先判断是否需要解压缩,然后再解析XML文本。

Android Java中包含了zip压缩解压缩工具库,可以从“java.util.zip”包中进行调用。我们看一下一个KMZ如何被解压缩:

URL url = new URL(strUrl);
HttpURLConnection uc = (HttpURLConnection) url.openConnection();

InputStream isKxml = null;

ZipInputStream zipIs = new ZipInputStream(uc.getInputStream());
ZipEntry zipEntry = null;
while ((zipEntry = zipIs.getNextEntry()) != null)
{
String zipEntryName = zipEntry.getName();
if (zipEntryName.endsWith("kml"))
{
ByteArrayOutputStream os = new ByteArrayOutputStream();
byte[] b = new byte[512];
int readedByteSize = 0;
while ((readedByteSize = zipIs.read(b)) > 0)
{
os.write(b, 0, readedByteSize);
}
os.flush();
os.close();

isKxml = new ByteArrayInputStream(os.toByteArray());
}
else if (zipEntryName.endsWith("png"))
{
ByteArrayOutputStream os = new ByteArrayOutputStream();
byte[] b = new byte[512];
int readedByteSize = 0;
while ((readedByteSize = zipIs.read(b)) > 0)
{
os.write(b, 0, readedByteSize);
}
os.flush();
os.close();

InputStream isBitmap = new ByteArrayInputStream(os
.toByteArray());
Bitmap bitmap = BitmapFactory.decodeStream(isBitmap);
kml.addBitmap(zipEntryName, bitmap);
isBitmap.close();
}
}
zipIs.close();

Reader reader = new InputStreamReader(isKxml);
parseKxml(kml, reader);//解析KML文本的方法
isKxml.close();
reader.close();

好了,解压缩完成后,重点就在解析KML文本上了。鉴于移动终端的KML内容不应该很大,因此在这里使用了XmlDocument方法解析,下面看一下方法:

private static void parseKxml(Kml kml, Reader reader) throws Exception
{
KXmlParser kXmlParser = new KXmlParser();
kXmlParser.setInput(reader);
Document doc = new Document();
doc.parse(kXmlParser);

if (doc == null) return;

Element eRoot = doc.getRootElement();
……(处理XML Element)
}

更多相关文章

  1. 为什么要学习 Markdown?究竟有什么用?
  2. Android(安卓)Log系统详解
  3. 在cocos2dx里访问/互调android里的activity方法/变量
  4. Android单元测试最简单使用
  5. Android基础 : Android(安卓)Service[转]
  6. Android(安卓)HTTP实例 使用GET方法和POST方法发送请求
  7. Android(安卓)SQLite教程:内部架构及SQLite使用办法
  8. Android(安卓)RecyclerView嵌套的滑动冲突问题
  9. 利用WebView通过javascript调用android java方法

随机推荐

  1. Android剪贴板
  2. Android 8.0 报错 android.os.FileUriExp
  3. 为什么在AndroidManifest.xml中Activity
  4. Android DrawerLayout实现抽屉效果实例代
  5. 编译android出错
  6. android实现截屏功能
  7. Android之SQLite学习
  8. android技术内幕心得
  9. wifi 通知栏上 选择程序时出现你的应用
  10. [android]初始化代码仓库时出现“OSError