J2ME KXML 解析中文xml代码示例

1、首先需要在你的工程资源中引入kxml.zip(kxml 1.21 stable version)

http://kxml.objectweb.org/software/downloads/

2、然后你建立一个httpconnection发送url请求,返回为in

3、最后解析in内容,如果包含中文内容,注意需要设置读入字节格式为UTF-8,否则会出现乱码。

比如从google cn上寻找一个酒店,需要获取其名字,地址,电话,坐标信息,输出格式为kml,url请求为

http://ditu.google.cn/maps?output=kml&hl=zh-CN&sll=31.2309321,121.4755366&start=0&num=10&q=酒店

那么解析返回kml信息的代码片断如下:

public void parse(InputStream in) throws IOException {
System.out.println("Enter parse:in");
Reader reader = new InputStreamReader(in,"UTF-8");
XmlParser parser = new XmlParser(reader);
ParseEvent pe = null;
parser.skip();
parser.read(Xml.START_TAG, null, "kml");
parser.skip();
parser.read(Xml.START_TAG, null, "Folder");
boolean trucking = true;
//boolean first = true;
while (trucking) {
pe = parser.read();
if (pe.getType() == Xml.START_TAG) {
String name = pe.getName();
if (name.equals("Placemark")) {
String title, address, coordinates, snippet, tel;
title = address = coordinates = snippet = tel = null;
while ((pe.getType() != Xml.END_TAG) ||
(pe.getName().equals(name) == false)) {
pe = parser.read();
if (pe.getType() == Xml.START_TAG &&
pe.getName().equals("name")) {
pe = parser.read();
title = pe.getText();
}
else if (pe.getType() == Xml.START_TAG &&
pe.getName().equals("coordinates")) {
pe = parser.read();
coordinates = pe.getText();
}
else if (pe.getType() == Xml.START_TAG &&
pe.getName().equals("Snippet")) {
pe = parser.read();
snippet = pe.getText();
//简述的格式是 "address<br/>tel no"
int beg = snippet.indexOf("<");
int end = snippet.indexOf(">");
address = snippet.substring(0,beg);
tel = snippet.substring(end,snippet.length());
}
}

// 这里的Listener是处理xml解析结果的抽象接口,通常由对xml感兴趣的Form对象实现
mResultListener.itemParsed(title, address, coordinates, tel);
}
else {
while ((pe.getType() != Xml.END_TAG) ||
(pe.getName().equals(name) == false))
pe = parser.read();
}
}
if (pe.getType() == Xml.END_TAG &&
pe.getName().equals("kml"))
trucking = false;
}
}

你可能感兴趣的:(xml,Google)