Sony EriCSSon發(fā)布了更好支持企業(yè)級(jí)應(yīng)用程序開發(fā)的新JSR,這其中就包括J2ME Web Service 1.0(JSR 172),索尼愛立信的W600就支持了JSR172。本文講述如何使用JSR 172提供的API來解析xml。
我們知道JSR172是由兩個(gè)部分組成的:
1. 一個(gè)輕量級(jí)的標(biāo)準(zhǔn)XML解析器
2. Web Services的遠(yuǎn)程調(diào)用API
其中這個(gè)JSR172實(shí)現(xiàn)的輕量級(jí)的XML解析器是JAXP1.2(java API for XML PRocessing)的一個(gè)子集。我們可以查看WTK提供的API看到j(luò)2me-xml提供的類一共只有12個(gè),這說明這個(gè)輕量級(jí)的XML解析器是適合在移動(dòng)電話這種資源受限設(shè)備上運(yùn)行的。下面我們通過一個(gè)例子介紹如何使用JSR 172解析XML,首先我們需要預(yù)備一個(gè)XML文件放在項(xiàng)目當(dāng)中,內(nèi)容如下:
/* * Phone.java * * Created on 2005年8月6日, 下午9:40 * * To change this template, choose Tools Options and locate the template under * the Source Creation and Management node. Right-click the template and choose * Open. You can then make changes to the template in the Source Editor. */
/** * * @author Administrator */ public class Phone {
private String colour = ""; private String name = ""; /** Creates a new instance of Phone */ public Phone() { }
public String getColour() { return colour; }
public void setColour(String colour) { this.colour = colour; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public void startDocument() throws SAXException {}
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { System.out.println("the qName is "+qName); if(qName.equals("phone")) { Phone phone = new Phone(); phones.addElement(phone); }
tagStack.push(qName); System.out.println("the tag stack's length is "+tagStack.size()); }
public void characters(char[] ch, int start, int length) throws SAXException { String chars = new String(ch, start, length).trim(); System.out.println("the character is "+chars);