基类:
import java.io.ByteArrayInputStream; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; public abstract class BaseHandler extends DefaultHandler { public abstract boolean parse(byte[] byteAarray); public static void parserXml(BaseHandler baseHandler, byte[] byteAarray) throws Exception { if (byteAarray == null || byteAarray.length == 0) return; ByteArrayInputStream bis = new ByteArrayInputStream(byteAarray); SAXParserFactory factory = SAXParserFactory.newInstance(); factory.newSAXParser().parse(bis, baseHandler); bis.close(); } public abstract void characters(char[] ch, int start, int length) throws SAXException; public abstract void endDocument() throws SAXException; public abstract void endElement(String uri, String localName, String name) throws SAXException; public abstract void startDocument() throws SAXException; public abstract void startElement(String uri, String localName, String tagName, Attributes attributes) throws SAXException; }
使用jsr182解析xml,最主要的还是要实现characters()和startElement()方法。
startElement()方法中可以使用attributes.getValue("XXX")获得属性值;
characters()方法中使用String chars = new String(ch, start, length).trim();获得文本。
至于endElement()和endDocument()方法,可以在其中实现一些“收尾”工作。
具体的实现类可以参考下面这个类:
import java.util.Stack; import java.util.Vector; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import com.tlt.app.App; import com.tlt.model.Supplement; import com.tlt.model.User; import com.tlt.util.Consts; import com.tlt.view.SupplementPage; import com.tlt.view.item.Dialog; public class SupplementHandler extends BaseHandler { public boolean parse(byte[] byteAarray) { // TODO Auto-generated method stub try { super.parserXml(this, byteAarray); return true; } catch (Exception e) { e.printStackTrace(); return false; } } public void characters(char[] ch, int start, int length) throws SAXException { // TODO Auto-generated method stub String chars = new String(ch, start, length).trim(); // System.out.println("the character is "+chars); if(chars.length() > 0) { String tagName = (String)tagStack.peek();//查看栈顶对象而不移除它 Supplement current = (Supplement)supplements.lastElement(); //<message><head><messageId>20100825110225890</messageId><result>0000</result><encryptionType>0</encryptionType><md>bdc5e43a0368c0ea8400960ed75d088a</md></head><body><orderId>TX201008251102240001</orderId><billNo>20100825110225890</billNo><userId>50</userId><fundsAccount>33900</fundsAccount><time>20100825110224</time><reserve></reserve></body></message> if (tagName.equals("messageId")) { current.setMessageId(chars); }else if(tagName.equals("result")){ current.setResult(chars); }else if(tagName.equals("encryptionType")){ current.setEncryptionType(chars); }else if(tagName.equals("md")){ current.setMd(chars); } else if(tagName.equals("errorMsg")) { current.setErrorMsg(chars); }else if(tagName.equals("orderId")) { current.setOrderId(chars); }else if(tagName.equals("billNo")) { current.setBillNo(chars); }else if(tagName.equals("userId")) { current.setUserId(chars); }else if(tagName.equals("fundsAccount")) { current.setFundsAccount(chars); }else if(tagName.equals("time")) { current.setTime(chars); }else if(tagName.equals("reserve")) { current.setReserve(chars); } } } public void endDocument() throws SAXException { // TODO Auto-generated method stub Consts.hash.put("supplement", supplements.lastElement()); Supplement supplement=(Supplement)supplements.lastElement(); if(supplement.getResult().equals(Consts.result)){ SupplementPage.resultDialog=new Dialog(App.app.canvas,"消息","充值成功!",0); User user=(User)Consts.hash.get("user"); user.setFundsAccount(supplement.getFundsAccount()); Consts.hash.put("user", user);//更新user SupplementPage.reset(); }else{ SupplementPage.resultDialog=new Dialog(App.app.canvas,"消息","充值失败!"+supplement.getErrorMsg(),0); } supplements=null; } public void endElement(String uri, String localName, String name) throws SAXException { // TODO Auto-generated method stub tagStack.pop();//移除栈顶对象并作为此函数的值返回该对象 } public void startDocument() throws SAXException { // TODO Auto-generated method stub } private Stack tagStack = new Stack(); private Vector supplements = new Vector(); public void startElement(String uri, String localName, String tagName, Attributes attributes) throws SAXException { // TODO Auto-generated method stub if(tagName.equals("message")) { Supplement entity = new Supplement(); supplements.addElement(entity); }if (tagName.equals("lottery")) { LotterySimpleInfo instance=new LotterySimpleInfo(); instance.setWinTermNo(attributes.getValue("winTermNo")); instance.setLotteryResult(attributes.getValue("lotteryResult")); instance.setTermNo(attributes.getValue("termNo")); instance.setDeadLine(attributes.getValue("deadLine")); lotterys.addElement(instance); } tagStack.push(tagName); } }
用法:
BaseHandler handler=new LoginHandler(); handler.parse(data);