不同的包下有不同的文件:
MainActivity界面:
public class MainActivity extends Activity {
private static final String TAG = "XML";
private BookParser parser;
private List<Book> books;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button readBtn = (Button) findViewById(R.id.btn_read);
readBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
try {
InputStream is = getAssets().open("Books.xml");
// parser = new SaxBookParser(); //创建SaxBookParser实例
// parser = new DomBookParser();
parser=new PullBookParse();
books = parser.parser(is); //解析输入流
for (Book book : books) {
Log.i(TAG, book.toString());
}
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
}
});
}
}
2.公共类:
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 "Book [id=" + id + ", name=" + name + ", price=" + price + "]";
}
}
2.三种解析方式都必须实现下面的接口:
public interface BookParser {
public List<Book> parser(InputStream is) throws Exception;
public String serialize(List<Book> books) throws Exception;
}
解析方式一:SAX
eg:
public class SaxBookParser implements BookParser{
@Override
public List<Book> parser(InputStream is) throws Exception {
// TODO Auto-generated method stub
SAXParserFactory factory=SAXParserFactory.newInstance();//获取SAXParserFactory实例
SAXParser parser=factory.newSAXParser();//获取SAXParserFactory实例
MyHandler handler=new MyHandler();//实例化handler
parser.parse(is, handler);//根据自定义Handler规则解析输入流 ;
return handler.getBooks();
}
@Override
public String serialize(List<Book> books) throws Exception {
// TODO Auto-generated method stub
SAXTransformerFactory factory=(SAXTransformerFactory) TransformerFactory.newInstance();//去的SAXTransformerFaxtory实例
TransformerHandler handler=factory.newTransformerHandler();//从factory中获取TransformerHandler;
Transformer transformer =handler.getTransformer();//从handler中获取transformer
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
StringWriter writer=new StringWriter();
Result result=new StreamResult(writer);
handler.setResult(result);
String uri="";
String localName="";
handler.startDocument();
// handler.startElement(uri, localName, books, null);
handler.startElement(uri, localName, "books", null);
AttributesImpl attrs=new AttributesImpl();//负责存放元素的属性信息
char[] ch=null;
for(Book book:books){
attrs.clear();
//添加一个名为id的属性(type影响不大,这里设为string)
attrs.addAttribute(uri, localName, "id", "string", String.valueOf(book.getId()));
//开始一个book元素 关联上面设定的id属性
handler.startElement(uri, localName, "book", attrs);
//开始一个name元素 没有属性
handler.startElement(uri, localName, "name", null);
ch = String.valueOf(book.getName()).toCharArray();
//设置name元素的文本节点
handler.characters(ch, 0, ch.length);
handler.endElement(uri, localName, "name");
//开始一个price元素 没有属性
handler.startElement(uri, localName, "price", null);
ch = String.valueOf(book.getPrice()).toCharArray();
handler.characters(ch, 0, ch.length);
handler.endElement(uri, localName, "price");
handler.endElement(uri, localName, "book");
}
handler.endElement(uri, localName, "books");
handler.endDocument();
return writer.toString();
}
}
2.解析方式二:DOM
public class DomBookParser implements BookParser {
@Override
public List<Book> parser(InputStream is) throws Exception {
// TODO Auto-generated method stub
List<Book> books=new ArrayList<Book>();
DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
DocumentBuilder builder=factory.newDocumentBuilder();
Document doc=builder.parse(is);
Element rootElement=doc.getDocumentElement();
NodeList items=rootElement.getElementsByTagName("book");
for (int i = 0; i < items.getLength(); i++) {
Book book = new Book();
Node item = items.item(i);
NodeList properties = item.getChildNodes();
for (int j = 0; j < properties.getLength(); j++) {
Node property = properties.item(j);
String nodeName = property.getNodeName();
if (nodeName.equals("id")) {
book.setId(Integer.parseInt(property.getFirstChild().getNodeValue()));
} else if (nodeName.equals("name")) {
book.setName(property.getFirstChild().getNodeValue());
} else if (nodeName.equals("price")) {
book.setPrice(Float.parseFloat(property.getFirstChild().getNodeValue()));
}
}
books.add(book);
}
return books;
}
@Override
public String serialize(List<Book> books) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.newDocument(); //由builder创建新文档
Element rootElement = doc.createElement("books");
for (Book book : books) {
Element bookElement = doc.createElement("book");
bookElement.setAttribute("id", book.getId() + "");
Element nameElement = doc.createElement("name");
nameElement.setTextContent(book.getName());
bookElement.appendChild(nameElement);
Element priceElement = doc.createElement("price");
priceElement.setTextContent(book.getPrice() + "");
bookElement.appendChild(priceElement);
rootElement.appendChild(bookElement);
}
doc.appendChild(rootElement);
//取得TransformerFactory实例
TransformerFactory transFactory = TransformerFactory.newInstance();
//从transFactory获取Transformer实例
Transformer transformer = transFactory.newTransformer();
// 设置输出采用的编码方式
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
// 是否自动添加额外的空白
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
// 是否忽略XML声明
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
StringWriter writer = new StringWriter();
Source source = new DOMSource(doc);
Result result = new StreamResult(writer);
transformer.transform(source, result);
return writer.toString();
}
}
3.解析方式3:PULL
public class PullBookParse implements BookParser{
@Override
public List<Book> parser(InputStream is) throws Exception {
// TODO Auto-generated method stub
List<Book> books=null;
Book book=null;
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;
}
break;
}
eventType =parser.next();
}
return books;
}
@Override
public String serialize(List<Book> books) throws Exception {
// TODO Auto-generated method stub
XmlSerializer serializer =Xml.newSerializer();
StringWriter writer =new StringWriter();
serializer.startDocument("UTF-8",true);
serializer.startTag("", "books");
for(Book book:books){
serializer.startTag("", "book");
serializer.attribute("", "id", book.getId() + "");
serializer.startTag("", "name");
serializer.text(book.getName());
serializer.endTag("", "name");
serializer.startTag("", "price");
serializer.text(book.getPrice() + "");
serializer.endTag("", "price");
serializer.endTag("", "book");
}
serializer.endTag("", "books");
serializer.endDocument();
return writer.toString();
}
}
帮助类DefaultHandler:
public class MyHandler extends DefaultHandler{
private List<Book> books;
private Book book;
private StringBuilder builder;
//返回解析后得到的Book对象集合
public List<Book> getBooks(){
return books;
}
@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);
}
@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);//将字符长度设置为0 以便重新开始读取元素内的字符节点
}
}