您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
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; /** * 这个例子讲述了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 { //因为三种方法都要去解析XML所以可以使三种方法都实现该接口即可 public List<Person> getPersonsByParseXML(InputStream in) throws Exception; //创建出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(); // 得到一个集合,里面存放在XML文件中所有的person NodeList nodelist=root.getElementsByTagName("person"); // 在这块判断集合是否为空 或者集合的元素个数为0 if(nodelist==null || nodelist.getLength()==0){ return null; } //初始化集合 persons=new ArrayList<Person>(); //生成List集合的数据 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; //这个方法是获取person节点下面的所有节点 NodeList nodelist2=element.getChildNodes(); for(int k=0;k<nodelist2.getLength();k++){ Node node=nodelist2.item(k); //获取节点的名称 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解析直接进行解析 * @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); //返回解析之后生成的集合数据 return dh.getList(); } //自定义一个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: //创建集合 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; } }
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。