一、XML解析
通過繼承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類型的集合,然後實現解析功能。
Android JSON解析 http://www.linuxidc.com/Linux/2012-09/70928.htm
Android解析JSON方式 http://www.linuxidc.com/Linux/2013-03/80300.htm
Android 解析JSON數據格式 http://www.linuxidc.com/Linux/2013-01/78016.htm