常用的三种XML解析方式分别是:SAX解析器,PULL解析器,以及DOM解析器
SAX解析器是基于事件的解析器,主要是围绕着事件触发,以及事件的处理器来进行的。SAX解析方式的特点是解析速度快,占用内存小,但一旦开始解析需要将真个目录解析完。
PULL解析器同样是基于事件的解析器,但我们需要自己获取产生的事件然后做相应的操作,而不像SAX那样由处理器触发一种事件的方法,执行我们的代码。因此PULL更适合作为Android的解析。
借鉴与:http://blog.csdn.net/liuhe688/article/details/6415593
解析的XML为book.xml 放在assets:
<?xml version="1.0" encoding="utf-8"?> <books> <book> <id>1001</id> <name>Thinking In Java</name> <price>80.00</price> </book> <book> <id>1002</id> <name>Core Java</name> <price>90.00</price> </book> <book> <id>1003</id> <name>hello,Java</name> <price>100.00</price> </book> </books>
保存XML信息的代码:
package com.example.xml01; public class Book { private int id; private String name; private float price; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public float getPrice() { return price; } public void setPrice(float price) { this.price = price; } @Override public String toString() { return "Struct_Book [id=" + id + ", name=" + name + ", price=" + price + "]"; } }
package com.example.xml01; import java.io.InputStream; import java.util.List; public interface Bookparse { public List<Book> parse(InputStream is) throws Exception; public String serialize(List<Book> books) throws Exception; }
package com.example.xml01; 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; import android.R.integer; public class SaxBookParser implements Bookparse { @Override public List<Book> parse(InputStream is) throws Exception { SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser parser=factory.newSAXParser(); MyHandler handler= new MyHandler(); parser.parse(is, handler); return handler.getBook(); } @Override public String serialize(List<Book> books) throws Exception { // TODO Auto-generated method stub return null; } private class MyHandler extends DefaultHandler{ private List<Book> books; private Book book; private StringBuilder builder; public List<Book> getBook() { return books; } @Override public void endDocument() throws SAXException { // TODO Auto-generated method stub super.endDocument(); } @Override public void endElement(String uri, String localName, String qName) throws SAXException { // TODO Auto-generated method stub super.endElement(uri, localName, qName); if(localName.equals("id")) { book.setId(Integer.parseInt(builder.toString())); } else if(localName.equals("name")) { book.setName(builder.toString()); } else if(localName.equals("price")) { book.setPrice(Float.parseFloat(builder.toString())); } else if(localName.equals("book")) { books.add(book); } } @Override public void startDocument() throws SAXException { // TODO Auto-generated method stub super.startDocument(); books= new ArrayList<Book>(); builder= new StringBuilder(); } @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(localName.equals("book")) { book= new Book(); } builder.setLength(0); } @Override public void characters(char[] ch, int start, int length) throws SAXException { // TODO Auto-generated method stub super.characters(ch, start, length); builder.append(ch, start, length); // 内部被清空 重新赋值 System.out.println(builder.toString()); //System.out.println(builder.length()); //System.out.println("ch: "+ch.toString()); } } }
package com.example.xml01; import java.io.IOException; import java.io.InputStream; import java.util.List; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class MainActivity extends Activity { private Bookparse parser; private List<Book> books; private Button btn1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btn1= (Button)findViewById(R.id.button1); btn1.setOnClickListener(listener); } OnClickListener listener = new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub try { InputStream is = getAssets().open("book.xml"); parser= new SaxBookParser(); books = parser.parse(is); for(int i=0;i<books.size();i++) { System.out.println(books.toString()); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }; }
package com.example.xml02; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import org.xmlpull.v1.XmlPullParser; import android.util.Xml; public class PullBookParser implements Bookparse{ List<Book> books=null; Book book=null; @Override public List<Book> parse(InputStream is) throws Exception { XmlPullParser parser = Xml.newPullParser(); parser.setInput(is, "UTF-8"); int eventType = parser.getEventType(); while(eventType!=XmlPullParser.END_DOCUMENT) { switch (eventType) { case XmlPullParser.START_DOCUMENT: books= new ArrayList<Book>(); break; case XmlPullParser.START_TAG: if(parser.getName().equals("book")) { book= new Book(); } else if(parser.getName().equals("id")) { eventType= parser.next(); book.setId(Integer.parseInt(parser.getText())); } else if(parser.getName().equals("name")) { eventType= parser.next(); book.setName(parser.getText()); } else if(parser.getName().equals("price")) { eventType= parser.next(); book.setPrice(Float.parseFloat(parser.getText())); } break; case XmlPullParser.END_TAG: if(parser.getName().equals("book")) { books.add(book); book=null; } default: break; } eventType=parser.next(); } return books; } @Override public String serialize(List<Book> books) throws Exception { // TODO Auto-generated method stub return null; } }
package com.example.xml02; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.os.Bundle; import android.view.ActionMode; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class MainActivity extends Activity { private Button button=null; private List<Book> books; private PullBookParser parser; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button=(Button)findViewById(R.id.button1); button.setOnClickListener(listener); } OnClickListener listener = new OnClickListener() { @Override public void onClick(View v) { try { InputStream is = getAssets().open("book.xml"); parser = new PullBookParser(); books= parser.parse(is); for(int i=0;i<books.size();i++) { System.out.println(books.toString()); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }; }