通过继承org.xml.sax.helpers.DefaultHandler类,覆写characters(),startDocument(),startElement(),endElement()方法实现读取
characters() --------读取结点中的字段值
startDocument()------------进行读取的初始化
startElement()-------------为每次读取初始化
endElement()------------实现读取功能
以下是实现解析功能的源代码:
package org.hjw.service;
import java.util.ArrayList;
import java.util.List;
import org.hjw.model.Product;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class XML2Product extends DefaultHandler {
private Product product;
private List<Product> products;
StringBuffer buffer = new StringBuffer();
public List<Product> getProducts() {
return products;
}
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
buffer.append(ch, start, length);
super.characters(ch, start, length);
}
@Override
public void startDocument() throws SAXException {
products = new ArrayList<Product>();
}
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
if (localName.equals("product")) {
product = new Product();
}
super.startElement(uri, localName, qName, attributes);
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if (localName.equals("product")) {
products.add(product);
} else if (localName.equals("id")) {
product.setId(Integer.parseInt(buffer.toString().trim()));
buffer.setLength(0);
} else if (localName.equals("name")) {
product.setName(buffer.toString().trim());
buffer.setLength(0);
} else if (localName.equals("price")) {
product.setPrice(Float.parseFloat(buffer.toString().trim()));
buffer.setLength(0);
}
super.endElement(uri, localName, qName);
}
}
然后只需在主函数中:
InputStream is = getResources().openRawResource(R.raw.products);
XML2Product xml2Product = new XML2Product();
Android.util.Xml.parse(is, Xml.Encoding.UTF_8, xml2Product);
List<Product> products = xml2Product.getProducts();
打开输入流,通过工具类分析xml文件即可获得一个ArrayList类型的集合,然后实现解析功能。