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"; @Override protectedvoidonCreate(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:handleexception e.printStackTrace(); } } @Override publicbooleanonCreateOptionsMenu(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; } @Override publicStringtoString(){ 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{ @Override publicList<Person>getPersonsByParseXML(InputStreamis)throwsException{ //TODOAuto-generatedmethodstub List<Person>persons=null; DocumentBuilderFactoryfactory=DocumentBuilderFactory.newInstance(); DocumentBuilderbuilder=factory.newDocumentBuilder(); Documentdocument=builder.parse(is); //获取的是根元素persons Elementroot=document.getDocumentElement(); //得到一个集合,里面存放在XML文件中所有的person NodeListnodelist=root.getElementsByTagName("person"); //在这块判断集合是否为空或者集合的元素个数为0 if(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; } @Override publicStringgetXMLDocumentByPersons(List<Person>persons){ //TODOAuto-generatedmethodstub returnnull; } } 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{ @Override publicList<Person>getPersonsByParseXML(InputStreamin)throwsException{ //TODOAuto-generatedmethodstub SAXParserFactoryfactory=SAXParserFactory.newInstance(); SAXParserparser=factory.newSAXParser(); MySaxHandlerdh=newMySaxHandler(); parser.parse(in,dh); //返回解析之后生成的集合数据 returndh.getList(); } //自定义一个Handler继承自DefaultHandler然后重写其中的方法 classMySaxHandlerextendsDefaultHandler{ privateList<Person>persons; privateStringcurrent; privatePersonperson; @Override publicvoidstartDocument()throwsSAXException{ //TODOAuto-generatedmethodstub super.startDocument(); persons=newArrayList<Person>(); } @Override publicvoidendDocument()throwsSAXException{ //TODOAuto-generatedmethodstub super.endDocument(); } @Override publicvoidstartElement(Stringuri,StringlocalName,StringqName,Attributesattributes)throwsSAXException{ //TODOAuto-generatedmethodstub super.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; } } @Override publicvoidendElement(Stringuri,StringqName)throwsSAXException{ super.endElement(uri,qName); if("person".equals(localName)){ persons.add(person); }elseif("name".equals(localName)||"age".equals(localName)){ current=null; } } @Override publicvoidcharacters(char[]ch,intstart,intlength)throwsSAXException{ super.characters(ch,start,length); Strings=newString(ch,length); if("name".equals(current)){ person.setName(s); }elseif("age".equals(current)){ person.setAge(Integer.parseInt(s)); } } //返回persons publicList<Person>getList(){ returnpersons; } } @Override publicStringgetXMLDocumentByPersons(List<Person>persons){ //TODOAuto-generatedmethodstub returnnull; } } packagecom.minimax.xmlparsedemo; importjava.io.InputStream; importjava.util.ArrayList; importjava.util.List; importorg.xmlpull.v1.XmlPullParser; importorg.xmlpull.v1.XmlPullParserFactory; publicclassPullXmlServiceimplementsIXmlService{ @Override publicList<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; } @Override publicStringgetXMLDocumentByPersons(List<Person>persons){ //TODOAuto-generatedmethodstub returnnull; } }