您好,登錄后才能下訂單哦!
XML的三種解析方式:DOM、SAX、PULL解析
廢話不說上代碼:
package com.minimax.xmlparsedemo; import java.io.InputStream; import java.util.List; import android.os.Bundle; import android.app.Activity; import android.content.res.AssetManager; import android.util.Log; import android.view.Menu; import android.widget.TextView; /** * 這個(gè)例子講述了XML的解析和生成 * 解析使用了四種方式 * 1.DOM解析 * 2.SAX解析 * 3.PULL解析 * 4. * @author Administrator */ public class MainActivity extends Activity { private AssetManager mAssess; private InputStream is; private DomXmlService mDomService; private SaxXmlService mSaxService; private PullXmlService mPullService; private List<Person> persons; private static final String TAG="domparse"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView tv=(TextView) findViewById(R.id.tv); try { mAssess=getAssets(); is=mAssess.open("persons.xml"); //DOM解析 // mDomService=new DomXmlService(); // persons=mDomService.getPersonsByParseXML(is); //SAX解析 // mSaxService=new SaxXmlService(); // persons=mSaxService.getPersonsByParseXML(is); //PULL解析 mPullService=new PullXmlService(); persons=mPullService.getPersonsByParseXML(is); //測試 String str=""; for(Person p:persons){ Log.i(TAG, p.toString()); str+=p.toString(); System.out.println("msg.."+p.toString()); } tv.setText(str); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } } package com.minimax.xmlparsedemo; public class Person { public int id; public int age; public String name; public int getId() { return id; } public void setId(int id) { this.id = id; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Person [id=" + id + ", age=" + age + ", name=" + name + "]"; } } package com.minimax.xmlparsedemo; import java.io.InputStream; import java.util.List; public interface IXmlService { //因?yàn)槿N方法都要去解析XML所以可以使三種方法都實(shí)現(xiàn)該接口即可 public List<Person> getPersonsByParseXML(InputStream in) throws Exception; //創(chuàng)建出XML文檔 public String getXMLDocumentByPersons(List<Person> persons); } package com.minimax.xmlparsedemo; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class DomXmlService implements IXmlService { @Override public List<Person> getPersonsByParseXML(InputStream is) throws Exception { // TODO Auto-generated method stub List<Person> persons=null; DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); DocumentBuilder builder=factory.newDocumentBuilder(); Document document=builder.parse(is); //獲取的是根元素 persons Element root=document.getDocumentElement(); // 得到一個(gè)集合,里面存放在XML文件中所有的person NodeList nodelist=root.getElementsByTagName("person"); // 在這塊判斷集合是否為空 或者集合的元素個(gè)數(shù)為0 if(nodelist==null || nodelist.getLength()==0){ return null; } //初始化集合 persons=new ArrayList<Person>(); //生成List集合的數(shù)據(jù) for(int i=0;i<nodelist.getLength();i++){ Element node=(Element) nodelist.item(i); Person p=new Person(); int id=Integer.parseInt(node.getAttribute("id")); String name=getAttrText(node, "name"); String age=getAttrText(node, "age"); p.setAge(Integer.parseInt(age)); p.setName(name); p.setId(id); persons.add(p); } return persons; } public String getAttrText(Element element,String name){ String content=null; //這個(gè)方法是獲取person節(jié)點(diǎn)下面的所有節(jié)點(diǎn) NodeList nodelist2=element.getChildNodes(); for(int k=0;k<nodelist2.getLength();k++){ Node node=nodelist2.item(k); //獲取節(jié)點(diǎn)的名稱 String nodeName=node.getNodeName(); if(nodeName.equals(name)){ content=node.getTextContent(); } } return content; } @Override public String getXMLDocumentByPersons(List<Person> persons) { // TODO Auto-generated method stub return null; } } package com.minimax.xmlparsedemo; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; /** * 不必等到文檔加載完畢之后才去解析,SAX解析直接進(jìn)行解析 * @author Administrator * */ public class SaxXmlService implements IXmlService { @Override public List<Person> getPersonsByParseXML(InputStream in) throws Exception { // TODO Auto-generated method stub SAXParserFactory factory=SAXParserFactory.newInstance(); SAXParser parser=factory.newSAXParser(); MySaxHandler dh=new MySaxHandler(); parser.parse(in, dh); //返回解析之后生成的集合數(shù)據(jù) return dh.getList(); } //自定義一個(gè)Handler繼承自DefaultHandler 然后重寫其中的方法 class MySaxHandler extends DefaultHandler{ private List<Person> persons; private String current; private Person person; @Override public void startDocument() throws SAXException { // TODO Auto-generated method stub super.startDocument(); persons=new ArrayList<Person>(); } @Override public void endDocument() throws SAXException { // TODO Auto-generated method stub super.endDocument(); } @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { // TODO Auto-generated method stub super.startElement(uri, localName, qName, attributes); if("person".equals(localName)){ person=new Person(); person.setId(Integer.parseInt(attributes.getValue("id"))); }else if("name".equals(localName) || "age".equals(localName)){ current=localName; } } @Override public void endElement(String uri, String localName, String qName) throws SAXException { super.endElement(uri, localName, qName); if("person".equals(localName)){ persons.add(person); }else if("name".equals(localName) || "age".equals(localName)){ current=null; } } @Override public void characters(char[] ch, int start, int length) throws SAXException { super.characters(ch, start, length); String s=new String(ch, start, length); if("name".equals(current)){ person.setName(s); }else if("age".equals(current)){ person.setAge(Integer.parseInt(s)); } } //返回persons public List<Person> getList(){ return persons; } } @Override public String getXMLDocumentByPersons(List<Person> persons) { // TODO Auto-generated method stub return null; } } package com.minimax.xmlparsedemo; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserFactory; public class PullXmlService implements IXmlService { @Override public List<Person> getPersonsByParseXML(InputStream in) throws Exception { List<Person> persons=null; Person person=null; XmlPullParserFactory factory=XmlPullParserFactory.newInstance(); XmlPullParser parser=factory.newPullParser(); parser.setInput(in, "utf-8"); int type=parser.getEventType(); while(type!=XmlPullParser.END_DOCUMENT){ String tagName=parser.getName(); switch (type) { case XmlPullParser.START_DOCUMENT: //創(chuàng)建集合 persons=new ArrayList<Person>(); break; case XmlPullParser.START_TAG: if("person".equals(tagName)){ person=new Person(); String id=parser.getAttributeValue(0); person.setId(Integer.parseInt(id)); }else if("name".equals(tagName)){ person.setName(parser.nextText()); }else if("age".equals(tagName)){ person.setAge(Integer.parseInt(parser.nextText())); } break; case XmlPullParser.END_TAG: if("person".equals(tagName)){ persons.add(person); person=null; } break; default: break; } type=parser.next(); } return persons; } @Override public String getXMLDocumentByPersons(List<Person> persons) { // TODO Auto-generated method stub return null; } }
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。