Xml的三种解析方式

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;
	}

}

相关文章

引言 NOKIA 有句著名的广告语:“科技以人为本”。任何技术都是为了满足人的生产生活需要而产生的。具体...
Writer:BYSocket(泥沙砖瓦浆木匠) 微博:BYSocket 豆瓣:BYSocket Reprint it anywhere u want. 文章...
Writer:BYSocket(泥沙砖瓦浆木匠) 微博:BYSocket 豆瓣:BYSocket Reprint it anywhere u want. 文章...
http://blog.jobbole.com/79252/ 引言 NOKIA 有句著名的广告语:“科技以人为本”。任何技术都是为了满...
(点击上方公众号,可快速关注) 公众号:smart_android 作者:耿广龙|loonggg 点击“阅读原文”,可查看...
一、xml与xslt 相信所有人对xml都不陌生,其被广泛的应用于数据数据传输、保存与序列化中,是一种极为强...