项目终于告一段落了,在项目中学习了很多新知识,其中xml的解析就是一个,现在把xml知识记录一下。
xml代码
<devices> <!--用于支持Nokia-ui风格手机--> <!--非触屏--> <device> <identifier>Generic/M20C10-x-Nokia</identifier> <features>isVirtual</features> <description>A device that merely supports the MIDP 2.0 and CLDC 1.0 standards.</description> <capability name="ScreenSize" value="176x220"/> <capability name="FullCanvasSize" value="176x220"/> <capability name="CanvasSize" value="176x220"/> <capability name="IconSize" value="46x48" /> <capability name="JavaPlatform" value="MIDP/2.0,JTWI/1.0" /> <capability name="JavaConfiguration" value="CLDC/1.0" /> <capability name="JavaPackage" value="btapi, pdaapi, wmapi1.0, wmapi2.0, mmapi,m3g,nokia-ui, webservice,jsr75, jsr82, jsr120, jsr135, jsr184, jsr172, jsr205, jsr234, jsr226, jsr177, jsr179, jsr180, jsr211, jsr229, jsr238, jsr239, jsr256" /> <capability name="Network" value="GSM, GPRS, UMTS" /> <capability name="Frequency" value="900,1800,1900,2100" /> </device> </devices>
这个xml文件没有标准xml的声明信息, 添加上声明<?xml version="1.0" encoding="UTF-8" standalone="no"?>也同样可以解析。看你的需求吧!
package cn.aircom.test; /******************************************************************** * 项目名称 :j2me学习 J2me Xml Parser * @author [email protected] * Copyright 2010-2011 Liwenyu. All rights reserved * * 本程序只用于学习目的,不能用于商业目的。如有需要请联系作者 ********************************************************************/ import java.io.IOException; import java.io.InputStream; import org.kxml2.io.KXmlParser; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; public class XmlTest { public XmlTest() throws XmlPullParserException, IOException { parser(); } public static void main(String args[]) throws XmlPullParserException, IOException { new XmlTest(); } public void parser() throws XmlPullParserException, IOException { InputStream is = this.getClass().getResourceAsStream("/custom-devices.xml"); KXmlParser parser = new KXmlParser(); parser.setInput(is, null); int eventType = parser.getEventType(); while (eventType != XmlPullParser.END_DOCUMENT) { if (eventType == XmlPullParser.START_DOCUMENT) { } else if (eventType == XmlPullParser.END_DOCUMENT) { } else if (eventType == XmlPullParser.START_TAG) { System.out.println(" " + parser.getName()); int size = parser.getAttributeCount(); for (int i = 0; i < size; i++) { System.out.println(" " + parser.getAttributeName(i)); System.out.println(" " + parser.getAttributeValue(i)); } } else if (eventType == XmlPullParser.END_TAG) { System.out.println(" " + parser.getName()); } else if (eventType == XmlPullParser.TEXT) { System.out.println(" " + parser.getText()); } eventType = parser.next(); } } }
这个例子基本能满足一般的需求。