XML的三种解析方式:DOM、SAX、PULL解析

废话不说上代码:

packagecom.minimax.xmlparsedemo;importjava.io.InputStream;importjava.util.List;importandroid.os.Bundle;importandroid.app.Activity;importandroid.content.res.AssetManager;importandroid.util.Log;importandroid.view.Menu;importandroid.widget.TextView;/***这个例子讲述了XML的解析和生成*解析使用了四种方式*1.DOM解析*2.SAX解析*3.PULL解析*4.*@authorAdministrator*/publicclassMainActivityextendsActivity{privateAssetManagermAssess;privateInputStreamis;privateDomXmlServicemDomService;privateSaxXmlServicemSaxService;privatePullXmlServicemPullService;privateList<Person>persons;privatestaticfinalStringTAG="domparse";@OverrideprotectedvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);TextViewtv=(TextView)findViewById(R.id.tv);try{mAssess=getAssets();is=mAssess.open("persons.xml");//DOM解析//mDomService=newDomXmlService();//persons=mDomService.getPersonsByParseXML(is);//SAX解析//mSaxService=newSaxXmlService();//persons=mSaxService.getPersonsByParseXML(is);//PULL解析mPullService=newPullXmlService();persons=mPullService.getPersonsByParseXML(is);//测试Stringstr="";for(Personp:persons){Log.i(TAG,p.toString());str+=p.toString();System.out.println("msg.."+p.toString());}tv.setText(str);}catch(Exceptione){//TODO:handleexceptione.printStackTrace();}}@OverridepublicbooleanonCreateOptionsMenu(Menumenu){//Inflatethemenu;thisaddsitemstotheactionbarifitispresent.getMenuInflater().inflate(R.menu.main,menu);returntrue;}}packagecom.minimax.xmlparsedemo;publicclassPerson{publicintid;publicintage;publicStringname;publicintgetId(){returnid;}publicvoidsetId(intid){this.id=id;}publicintgetAge(){returnage;}publicvoidsetAge(intage){this.age=age;}publicStringgetName(){returnname;}publicvoidsetName(Stringname){this.name=name;}@OverridepublicStringtoString(){return"Person[id="+id+",age="+age+",name="+name+"]";}}packagecom.minimax.xmlparsedemo;importjava.io.InputStream;importjava.util.List;publicinterfaceIXmlService{//因为三种方法都要去解析XML所以可以使三种方法都实现该接口即可publicList<Person>getPersonsByParseXML(InputStreamin)throwsException;//创建出XML文档publicStringgetXMLDocumentByPersons(List<Person>persons);}packagecom.minimax.xmlparsedemo;importjava.io.InputStream;importjava.util.ArrayList;importjava.util.List;importjavax.xml.parsers.DocumentBuilder;importjavax.xml.parsers.DocumentBuilderFactory;importorg.w3c.dom.Document;importorg.w3c.dom.Element;importorg.w3c.dom.Node;importorg.w3c.dom.NodeList;publicclassDomXmlServiceimplementsIXmlService{@OverridepublicList<Person>getPersonsByParseXML(InputStreamis)throwsException{//TODOAuto-generatedmethodstubList<Person>persons=null;DocumentBuilderFactoryfactory=DocumentBuilderFactory.newInstance();DocumentBuilderbuilder=factory.newDocumentBuilder();Documentdocument=builder.parse(is);//获取的是根元素personsElementroot=document.getDocumentElement();//得到一个集合,里面存放在XML文件中所有的personNodeListnodelist=root.getElementsByTagName("person");//在这块判断集合是否为空或者集合的元素个数为0if(nodelist==null||nodelist.getLength()==0){returnnull;}//初始化集合persons=newArrayList<Person>();//生成List集合的数据for(inti=0;i<nodelist.getLength();i++){Elementnode=(Element)nodelist.item(i);Personp=newPerson();intid=Integer.parseInt(node.getAttribute("id"));Stringname=getAttrText(node,"name");Stringage=getAttrText(node,"age");p.setAge(Integer.parseInt(age));p.setName(name);p.setId(id);persons.add(p);}returnpersons;}publicStringgetAttrText(Elementelement,Stringname){Stringcontent=null;//这个方法是获取person节点下面的所有节点NodeListnodelist2=element.getChildNodes();for(intk=0;k<nodelist2.getLength();k++){Nodenode=nodelist2.item(k);//获取节点的名称StringnodeName=node.getNodeName();if(nodeName.equals(name)){content=node.getTextContent();}}returncontent;}@OverridepublicStringgetXMLDocumentByPersons(List<Person>persons){//TODOAuto-generatedmethodstubreturnnull;}}packagecom.minimax.xmlparsedemo;importjava.io.InputStream;importjava.util.ArrayList;importjava.util.List;importjavax.xml.parsers.SAXParser;importjavax.xml.parsers.SAXParserFactory;importorg.xml.sax.Attributes;importorg.xml.sax.SAXException;importorg.xml.sax.helpers.DefaultHandler;/***不必等到文档加载完毕之后才去解析,SAX解析直接进行解析*@authorAdministrator**/publicclassSaxXmlServiceimplementsIXmlService{@OverridepublicList<Person>getPersonsByParseXML(InputStreamin)throwsException{//TODOAuto-generatedmethodstubSAXParserFactoryfactory=SAXParserFactory.newInstance();SAXParserparser=factory.newSAXParser();MySaxHandlerdh=newMySaxHandler();parser.parse(in,dh);//返回解析之后生成的集合数据returndh.getList();}//自定义一个Handler继承自DefaultHandler然后重写其中的方法classMySaxHandlerextendsDefaultHandler{privateList<Person>persons;privateStringcurrent;privatePersonperson;@OverridepublicvoidstartDocument()throwsSAXException{//TODOAuto-generatedmethodstubsuper.startDocument();persons=newArrayList<Person>();}@OverridepublicvoidendDocument()throwsSAXException{//TODOAuto-generatedmethodstubsuper.endDocument();}@OverridepublicvoidstartElement(Stringuri,StringlocalName,StringqName,Attributesattributes)throwsSAXException{//TODOAuto-generatedmethodstubsuper.startElement(uri,localName,qName,attributes);if("person".equals(localName)){person=newPerson();person.setId(Integer.parseInt(attributes.getValue("id")));}elseif("name".equals(localName)||"age".equals(localName)){current=localName;}}@OverridepublicvoidendElement(Stringuri,StringlocalName,StringqName)throwsSAXException{super.endElement(uri,localName,qName);if("person".equals(localName)){persons.add(person);}elseif("name".equals(localName)||"age".equals(localName)){current=null;}}@Overridepublicvoidcharacters(char[]ch,intstart,intlength)throwsSAXException{super.characters(ch,start,length);Strings=newString(ch,start,length);if("name".equals(current)){person.setName(s);}elseif("age".equals(current)){person.setAge(Integer.parseInt(s));}}//返回personspublicList<Person>getList(){returnpersons;}}@OverridepublicStringgetXMLDocumentByPersons(List<Person>persons){//TODOAuto-generatedmethodstubreturnnull;}}packagecom.minimax.xmlparsedemo;importjava.io.InputStream;importjava.util.ArrayList;importjava.util.List;importorg.xmlpull.v1.XmlPullParser;importorg.xmlpull.v1.XmlPullParserFactory;publicclassPullXmlServiceimplementsIXmlService{@OverridepublicList<Person>getPersonsByParseXML(InputStreamin)throwsException{List<Person>persons=null;Personperson=null;XmlPullParserFactoryfactory=XmlPullParserFactory.newInstance();XmlPullParserparser=factory.newPullParser();parser.setInput(in,"utf-8");inttype=parser.getEventType();while(type!=XmlPullParser.END_DOCUMENT){StringtagName=parser.getName();switch(type){caseXmlPullParser.START_DOCUMENT://创建集合persons=newArrayList<Person>();break;caseXmlPullParser.START_TAG:if("person".equals(tagName)){person=newPerson();Stringid=parser.getAttributeValue(0);person.setId(Integer.parseInt(id));}elseif("name".equals(tagName)){person.setName(parser.nextText());}elseif("age".equals(tagName)){person.setAge(Integer.parseInt(parser.nextText()));}break;caseXmlPullParser.END_TAG:if("person".equals(tagName)){persons.add(person);person=null;}break;default:break;}type=parser.next();}returnpersons;}@OverridepublicStringgetXMLDocumentByPersons(List<Person>persons){//TODOAuto-generatedmethodstubreturnnull;}}



附件:http://down.51cto.com/data/2365564