欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

J2ME解析并读取xml文件

程序员文章站 2024-03-24 11:28:58
...
[color=green]用KXML解析读取xml文本[/color]
首先需要kxml2-2.3.0.jar,可以在我的附件中下载,源代码如下:

[img]http://dl.iteye.com/upload/attachment/211767/455090ee-fb60-3445-8ba4-02c7b68b2d72.png[/img]



import java.io.IOException;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;

import org.kxml2.io.KXmlParser;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;


public class KXML_ZHMidlet extends MIDlet implements CommandListener{

private Display display;
private Form form;

public final static Command exitCommand = new Command("Exit",Command.EXIT,1);

public KXML_ZHMidlet(){
display = Display.getDisplay(this);
form = new Form("中文读取本地xml文件");
form.addCommand(exitCommand);
form.setCommandListener(this);
}



protected void destroyApp(boolean unconditional)
throws MIDletStateChangeException {

}

protected void pauseApp() {

}

protected void startApp() throws MIDletStateChangeException {
try {
readXML();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
display.setCurrent(form);
}

public void commandAction(Command c, Displayable d) {

}


public void readXML() throws XmlPullParserException{

KXmlParser parser = new KXmlParser();
// parser.setInput(this.getClass().getResourceAsStream("/a.xml"),null);
parser.setInput(this.getClass().getResourceAsStream("/xiaochao.xml"),null);
int eventType = parser.getEventType();

try{

while(eventType != XmlPullParser.END_DOCUMENT){
//当标签为开始标签并且标签内容为xiaochao时
if(eventType == XmlPullParser.START_TAG && parser.getName().equals("person")){
//读取第一个属性,
form.append("魔兽游戏: " + parser.getAttributeValue(0) +"\n");
//读取下一个标签
eventType = parser.nextTag();
if(parser.getName().equals("name")){
//提取name标签的内容
form.append("英雄: " +parser.nextText()+"\n");
}
//读取下一个标签
eventType = parser.nextTag();
if(parser.getName().equals("attack")){
//提取name标签的内容
form.append("专属装备: " +parser.nextText()+"\n");
}

form.append("\n");
}

eventType = parser.next();
}











}catch(IOException e){
e.printStackTrace();
}

form.append("读取文件完毕!");


}


}




[color=green]xiaochao.xml文件内容[/color]


<?xml version="1.0" encoding="UTF-8"?>
<xiaochao>
<person version='Dota'>
<name>雷电男</name>
<attack>雷神装备</attack>
</person>
<person version='真三'>
<name>马岱</name>
<attack>月下美装备</attack>
</person>
</xiaochao>