大橙子网站建设,新征程启航
为企业提供网站建设、域名注册、服务器等服务
XML的三种解析方式:DOM、SAX、PULL解析
创新互联建站是一家专注网站建设、网络营销策划、小程序设计、电子商务建设、网络推广、移动互联开发、研究、服务为一体的技术型公司。公司成立10多年以来,已经为上千家成都石凉亭各业的企业公司提供互联网服务。现在,服务的上千家客户与我们一路同行,见证我们的成长;未来,我们一起分享成功的喜悦。
废话不说上代码:
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; /** * 这个例子讲述了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 Listpersons; 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 { //因为三种方法都要去解析XML所以可以使三种方法都实现该接口即可 public List getPersonsByParseXML(InputStream in) throws Exception; //创建出XML文档 public String getXMLDocumentByPersons(List 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 getPersonsByParseXML(InputStream is) throws Exception { // TODO Auto-generated method stub List persons=null; DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); DocumentBuilder builder=factory.newDocumentBuilder(); Document document=builder.parse(is); //获取的是根元素 persons Element root=document.getDocumentElement(); // 得到一个集合,里面存放在XML文件中所有的person NodeList nodelist=root.getElementsByTagName("person"); // 在这块判断集合是否为空 或者集合的元素个数为0 if(nodelist==null || nodelist.getLength()==0){ return null; } //初始化集合 persons=new ArrayList (); //生成List集合的数据 for(int i=0;i 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解析直接进行解析 * @author Administrator * */ public class SaxXmlService implements IXmlService { @Override public List 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); //返回解析之后生成的集合数据 return dh.getList(); } //自定义一个Handler继承自DefaultHandler 然后重写其中的方法 class MySaxHandler extends DefaultHandler{ private List persons; private String current; private Person person; @Override public void startDocument() throws SAXException { // TODO Auto-generated method stub super.startDocument(); persons=new ArrayList (); } @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 getList(){ return persons; } } @Override public String getXMLDocumentByPersons(List 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 getPersonsByParseXML(InputStream in) throws Exception { List 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: //创建集合 persons=new ArrayList (); 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 persons) { // TODO Auto-generated method stub return null; } }