J2ME解析并读取xml文件

用KXML解析读取xml文本
首先需要kxml2-2.3.0.jar,可以在我的附件中下载,源代码如下:

J2ME解析并读取xml文件


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("读取文件完毕!");
		
		
	}
	
	
}




xiaochao.xml文件内容

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



你可能感兴趣的:(eclipse,游戏,xml,sun)