KXML是一个只占很小存储空间的XML语法分析程序,对于J2ME应用程序非常适合。它有一个非常独特的DOM操作方法和被称为Pull的语法分析方法。
WTK下载地址:http://java.sun.com/products/j2mewtoolkit/download-2_0.html
Kxml下载地址:http://kxml.objectweb.org/software/downloads/
实例分析(通过Pull,Dom方式解析xml)
(1)Pull语法分析
- import java.io.IOException;
- import org.kxml2.io.KXmlParser;
- import org.xmlpull.v1.XmlPullParser;
- import org.xmlpull.v1.XmlPullParserException;
- public class TestPull {
- public static void main(String args[]) throws XmlPullParserException,
- IOException {
- KXmlParser parser = new KXmlParser();
- parser.setInput(new TestPull().getClass().getResourceAsStream(
- "/test.xml"), "UTF-8");
- parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
- int eventType = parser.getEventType();
- while (eventType != XmlPullParser.END_DOCUMENT) {
- if (eventType == XmlPullParser.START_DOCUMENT) {
- System.out.println("Start document");
- } else if (eventType == XmlPullParser.END_DOCUMENT) {
- System.out.println("End document");
- } else if (eventType == XmlPullParser.START_TAG) {
- System.out.println(parser.getName());
- System.out
- .println("Start Count: " + parser.getAttributeCount());
- 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();
- }
- }
- }
(2)Dom方式
- import org.kxml2.io.KXmlParser;
- import org.kxml2.kdom.Document;
- import org.kxml2.kdom.Element;
- public class TestDom {
- public static void main(String args[]) {
- KXmlParser parser = new KXmlParser();
- Document doc = new Document();
- try {
- parser.setInput(TestDom.class.getResourceAsStream("test.xml"), "UTF-8");
- doc.parse(parser);
- } catch (Exception e) {
- e.printStackTrace();
- }
- Element root = doc.getRootElement();
- traverse(root);
- }
- private static void traverse(Element element) {
- for (int i = 0; i < element.getAttributeCount(); i++) {
- System.out.println("Attribute:" + element.getAttributeName(i)
- + "=" + element.getAttributeValue(i));
- }
- for (int i = 0; i < element.getChildCount(); i++) {
- if (element.isText(i)) {
- if (!element.getText(i).trim().equals(""))
- System.out.println("Text:" + element.getText(i));
- } else {
- if (element.getType(i) == Element.COMMENT) {
- System.out.println("comment:" + element.getChild(i));
- } else if (element.getType(i) == Element.ELEMENT) {
- traverse(element.getElement(i));
- }else{
- System.out.println(element.getType(i));
- }
- }
- }
- }
- }
附注:
KXML是一个Enhydra维护的项目,支持下面的性能:
1、支持XML名称空间
2、用"松散"模式分析HTML或其它SGML格式
3、占用很少的存储空间(21 kbps)
4、基于Pull的分析
5、支持XML写操作
6、可选的DOM支持
7、可选的WAP支持