最近做项目,服务器传过来的都是Xml格式的数据,需要解析xml,本来使用的是jsr182这个包,没问题(唯一不足的是手机顽童不支持jsr182,当碰到解析xml数据时,模拟器一闪而过!)。后来看到KXML这个第三方包,听说效率不错,于是用了,结果导入该jar包后总是出现java.lang.NoClassDefFoundError: org/xmlpull/v1/XmlPullParserException
很是郁闷!于是干脆下载了源代码,把源代码copy到工程中,运行没问题。
另外nanoXML也可以解析xml,它是一次性加载数据然后解析,当数据量大的时候估计内存吃不消。还有nanoXML的源码中怎么有j2se的类?直接导致我彻底放弃nanoXML。
下面是我用KXML做的代码,大家可以参考:
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import org.kxml2.io.KXmlParser;
import org.xmlpull.v1.XmlPullParserException;
public class Connection implements Runnable{
private boolean isProxy = false; //是否使用代理
private HttpConnection conn=null;
private String url;
private String sendDate;
private int connTimes = 0;
public Connection(String url,String sendDate){
this.url=url;
this.sendDate=sendDate;
}
private void send(){
InputStream is = null;
try{
if(isProxy){//使用代理
System.out.println("启用http代理连接");
conn = (HttpConnection) Connector.open("http://10.0.0.172/");
conn.setRequestMethod(HttpConnection.GET);
conn.setRequestProperty("X-Online-Host", url);
conn.setRequestProperty("User-Agent", "Profile/MIDP-2.0 Configuration/CLDC-1.0");
//Proxy-Connection不是RFC标准,但是很多服务器都这么用了
conn.setRequestProperty("Proxy-Connection", "Keep-Alive");
}else{
System.out.println("启用直连");
conn = (HttpConnection) Connector.open("http://"+url);
conn.setRequestMethod(HttpConnection.GET);
conn.setRequestProperty("User-Agent", "Nokia6500s-1/2.0");
conn.setRequestProperty("X-Up-Calling-Line-ID","13761083826");
}
// Connection是针对HTTP1.0的标准,HTTP1.1默认就是keep-alive的,并且该头不允许在1.1里面使用
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type","text/xml;charset=UTF-8");
if(sendDate!=null){
//发送数据
conn.setRequestProperty("Content-Length",String.valueOf(sendDate.length()));
DataOutputStream dos = new DataOutputStream(conn.openOutputStream());
dos.write(sendDate.getBytes("UTF-8"));
dos.flush();
dos.close();
}
//接收数据
if(conn.getResponseCode()==HttpConnection.HTTP_OK){
is=conn.openInputStream();
/*
int length = (int) conn.getLength();
System.out.println("length="+length);
byte[] data=null;
DataInputStream dis=new DataInputStream(is);
if (length == -1) {
int chunkSize = 1500;
byte[] buffer = new byte[chunkSize];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int dataSizeRead = 0;// size of data read from input stream.
while ((dataSizeRead = is.read(buffer)) != -1) {
baos.write(buffer, 0, dataSizeRead);
}
data = baos.toByteArray();
baos.close();
} else if (length == 0) {
} else {// known length
data = new byte[length];
dis.readFully(data);
}
String text=null;
try {
text=new String(data, "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("[收到数据]"+text);
*/
parseXml(is);
}else{
System.out.println("无法连接服务器,返回码:"+conn.getResponseCode());
}
}catch (Exception e) {
// TODO: handle exception
System.out.println("重新尝试连接:"+(connTimes+1));
if (connTimes < 2) { connTimes++;
isProxy=!isProxy;//
send();
} else {
connTimes = 0;
System.out.println("无法连接服务器");
// Consts.isWaiting=false;
// Consts.hasError=true;
}
}finally{
try {
if (is != null)
is.close();
if (conn != null)
conn.close();
} catch (Throwable t) {
System.out.println("Exception occurred while closing input stream.");
}
}
}
private void parseXml(InputStream is){
KXmlParser parser = new KXmlParser();
try {
parser.setInput(is,"UTF-8");
int eventType=parser.getEventType();
System.out.println("eventType="+eventType);
if(eventType==KXmlParser.START_DOCUMENT){
startDocument(parser);
}
boolean keepParsing = true;
while(keepParsing){
int type = parser.next();
switch(type){
case KXmlParser.START_DOCUMENT:
//startDocument(parser);//这里总是执行不到,可以去掉
break;
case KXmlParser.START_TAG:
startElement(parser);
break;
case KXmlParser.END_TAG:
endElement(parser);
break;
case KXmlParser.TEXT:
characters(parser);
break;
case KXmlParser.END_DOCUMENT:
endDocument(parser);
keepParsing = false;
break;
}
}
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void startDocument(KXmlParser parser){
}
public void endDocument(KXmlParser parser){
}
String tagName=null;
public void startElement(KXmlParser parser){
this.tagName = parser.getName();
System.out.println("key:" + this.tagName);
int attributeCount= parser.getAttributeCount();
String winTermNo=parser.getAttributeValue(null, "winTermNo");
System.out.println("winTermNo="+winTermNo);
// for(int i=0;i<attributeCount;i++){
// System.out.println(parser.getAttributeName(i)+":"+parser.getAttributeValue(i));
// }
}
public void endElement(KXmlParser parser){
}
public void characters(KXmlParser parser){
String content = parser.getText();
System.out.println(tagName + ":" + content);
if (tagName.equals("lottery")){
System.out.println(content);
}
else if(tagName.equals("gameInfo")){
System.out.println(content);
}
this.tagName = null;
}
public void run() {
// TODO Auto-generated method stub
send();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Connection c=new Connection("127.0.0.1:8080/Lottery/kjava.portal?action=lotterySimpleInfo",null);
Thread t=new Thread(c);
t.start();
}
}
当然,像上面的startXXX(),endXXX()需要自己实现,最好做成接口!
我访问上面的地址返回的xml为:
<message>
<lottery winTermNo="10098" lotteryResult="0409152528|0405" termNo="10099" deadLine="20100825193000" />
<lottery winTermNo="10228" lotteryResult="000" termNo="10229" deadLine="20100824193000" />
<lottery winTermNo="10228" lotteryResult="00000" termNo="10229" deadLine="20100824193000" />
<lottery winTermNo="10098" lotteryResult="2268381" termNo="10099" deadLine="20100824193000" />
<lottery winTermNo="10073" lotteryResult="33333333333333" termNo="" deadLine="" />
<gameInfo id="1" homeTeam="阿尔科孔" awayTeam="塞尔塔" gameDate="08-30 11:51" leagueMatch="国王杯" />
<gameInfo id="2" homeTeam="皇家贝蒂斯" awayTeam="萨拉曼卡" gameDate="08-30 11:51" leagueMatch="国王杯" />
<gameInfo id="3" homeTeam="弗鲁米嫩塞" awayTeam="帕尔梅拉斯" gameDate="08-30 11:51" leagueMatch="巴甲" />
<gameInfo id="4" homeTeam="弗鲁米嫩塞" awayTeam="帕尔梅拉斯" gameDate="08-30 11:51" leagueMatch="巴甲" />
<gameInfo id="5" homeTeam="弗鲁米嫩塞" awayTeam="帕尔梅拉斯" gameDate="08-30 11:51" leagueMatch="巴甲" />
<gameInfo id="6" homeTeam="弗鲁米嫩塞" awayTeam="帕尔梅拉斯" gameDate="08-30 11:51" leagueMatch="巴甲" />
<gameInfo id="7" homeTeam="弗鲁米嫩塞" awayTeam="帕尔梅拉斯" gameDate="08-30 11:51" leagueMatch="巴甲" />
<gameInfo id="8" homeTeam="弗鲁米嫩塞" awayTeam="帕尔梅拉斯" gameDate="08-30 11:51" leagueMatch="巴甲" />
<gameInfo id="9" homeTeam="弗鲁米嫩塞" awayTeam="帕尔梅拉斯" gameDate="08-30 11:51" leagueMatch="巴甲" />
<gameInfo id="10" homeTeam="弗鲁米嫩塞" awayTeam="帕尔梅拉斯" gameDate="08-30 11:51" leagueMatch="巴甲" />
<gameInfo id="11" homeTeam="弗鲁米嫩塞" awayTeam="帕尔梅拉斯" gameDate="08-30 11:51" leagueMatch="巴甲" />
<gameInfo id="12" homeTeam="弗鲁米嫩塞" awayTeam="帕尔梅拉斯" gameDate="08-30 11:51" leagueMatch="巴甲" />
<gameInfo id="13" homeTeam="弗鲁米嫩塞" awayTeam="帕尔梅拉斯" gameDate="08-30 11:51" leagueMatch="巴甲" />
<gameInfo id="14" homeTeam="弗鲁米嫩塞" awayTeam="帕尔梅拉斯" gameDate="08-30 11:51" leagueMatch="巴甲" />
</message>
最后,提供KXML源码: