在项目开发中我们可能需要读取服务器,并从服务器解析相关数据,而XML文件格式为数据的存储提供了很多方便,因此,掌握XML的解析方式,至少一种解析方式将为网络项目的开发起到如虎添翼的作用。本文采用SAX解析一个xml文件用于演示SAX解析xml文件的操作:
1:界面的设计
如图,界面中有一个按钮和一个TextView控件,程序要实现如下功能:
点击解析按钮时解析程序中raw目录下的一个orders.xml文件,并将解析结果显示到TexView控件上。
2: XML文件内容
2: XML文件内容
如图示 ,orders.xml文件中存储了一个菜谱的数据,其中包括了菜的ID,菜名,菜照片名,菜价格和一些详细信息。
3:代码设计
程序中SAX数据解析部分主要提供了两个类,一个是MyHandler类,另一个是ReadXML类,前一个雷未后一个类所使用,MyHandler类程序代码如下:
package com.study.SAX;
3:代码设计
程序中SAX数据解析部分主要提供了两个类,一个是MyHandler类,另一个是ReadXML类,前一个雷未后一个类所使用,MyHandler类程序代码如下:
package com.study.SAX;
import java.util.ArrayList;
import java.util.List;
import java.util.List;
import org.xml.sax.Attributes;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import com.study.order.Order;;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import com.study.order.Order;;
public class MyHandler extends DefaultHandler{
private static final String TAG = "MyHandler";
private static final boolean D = true;
protected List<Order> orders = null;;
private Order order = null;
private StringBuffer buff = null;
boolean buffering = false;
public MyHandler() { }
public void setOrders(List<Order> ordersTemp) {
this.orders = ordersTemp;
}
public List<Order> getOrders() {
return this.orders;
}
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
buff.append(ch,start,length);
}
@Override
public void endDocument() throws SAXException {
if(D) {
System.out.println(TAG + " 4-->end document...");
}
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if(D) {
System.out.println(TAG+" 3--->End element...");
}
if(localName.equals("order")) {
orders.add(order);
}
else if(localName.equals("name")) {
order.setName(buff.toString().trim());
}
else if(localName.equals("photo")) {
order.setPhotoName(buff.toString().trim());
}
else if(localName.equals("price")) {
order.setPrice(Double.parseDouble(buff.toString().trim()));
}
else if(localName.equals("detil")) {
order.setDetil(buff.toString().trim());
}
}
@Override
public void setDocumentLocator(Locator locator) {
}
@Override
public void startDocument() throws SAXException {
buff = new StringBuffer();
if(D) {
System.out.println(TAG+" 1---->Start document...");
}
}
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
if(D) {
System.out.println(qName + " 2--->Start..."+attributes.getIndex("id"));
}
buff.delete(0, buff.length()); //请除当前buff里面的内容
if(localName.equals("order-list")) {
orders = new ArrayList<Order>();
}
else if(localName.equals("order")) {
order = new Order();
}
if(attributes.getIndex("id") != -1) {
order.setID(Integer.parseInt(attributes.getValue("id").trim()));
}
}
}
ReadXML类代码如下:他需要一个inputStream的对象用于创建数据输入源,同时程序中返回一个Order类的集合orders。程序详细代码如下:
package com.study.SAX;
private static final String TAG = "MyHandler";
private static final boolean D = true;
protected List<Order> orders = null;;
private Order order = null;
private StringBuffer buff = null;
boolean buffering = false;
public MyHandler() { }
public void setOrders(List<Order> ordersTemp) {
this.orders = ordersTemp;
}
public List<Order> getOrders() {
return this.orders;
}
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
buff.append(ch,start,length);
}
@Override
public void endDocument() throws SAXException {
if(D) {
System.out.println(TAG + " 4-->end document...");
}
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if(D) {
System.out.println(TAG+" 3--->End element...");
}
if(localName.equals("order")) {
orders.add(order);
}
else if(localName.equals("name")) {
order.setName(buff.toString().trim());
}
else if(localName.equals("photo")) {
order.setPhotoName(buff.toString().trim());
}
else if(localName.equals("price")) {
order.setPrice(Double.parseDouble(buff.toString().trim()));
}
else if(localName.equals("detil")) {
order.setDetil(buff.toString().trim());
}
}
@Override
public void setDocumentLocator(Locator locator) {
}
@Override
public void startDocument() throws SAXException {
buff = new StringBuffer();
if(D) {
System.out.println(TAG+" 1---->Start document...");
}
}
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
if(D) {
System.out.println(qName + " 2--->Start..."+attributes.getIndex("id"));
}
buff.delete(0, buff.length()); //请除当前buff里面的内容
if(localName.equals("order-list")) {
orders = new ArrayList<Order>();
}
else if(localName.equals("order")) {
order = new Order();
}
if(attributes.getIndex("id") != -1) {
order.setID(Integer.parseInt(attributes.getValue("id").trim()));
}
}
}
ReadXML类代码如下:他需要一个inputStream的对象用于创建数据输入源,同时程序中返回一个Order类的集合orders。程序详细代码如下:
package com.study.SAX;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import org.xml.sax.XMLReader;
import com.study.order.Order;
public class ReadXML {
protected List<Order> orders = null;
protected InputStream is = null;
protected List<Order> orders = null;
protected InputStream is = null;
public ReadXML() { }
public ReadXML(List<Order> ordersTemp,InputStream isTrmp) {
this.orders = ordersTemp;
this.is = isTrmp;
}
public ReadXML(List<Order> ordersTemp,InputStream isTrmp) {
this.orders = ordersTemp;
this.is = isTrmp;
}
public void setOrders(List<Order> ordersTemp) {
this.orders = ordersTemp;
}
public List<Order> getOrders() {
return this.orders;
}
public void setIs(InputStream isTemp) {
this.is = isTemp;
}
public InputStream getIs() {
return this.is;
}
this.orders = ordersTemp;
}
public List<Order> getOrders() {
return this.orders;
}
public void setIs(InputStream isTemp) {
this.is = isTemp;
}
public InputStream getIs() {
return this.is;
}
public List<Order> readFromIs() {
if(orders == null) {
orders = new ArrayList<Order>();
// System.out.println("5-->empty point...");
}
try{
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
XMLReader xmlReader = parser.getXMLReader();
MyHandler handler = new MyHandler();
xmlReader.setContentHandler(handler);
xmlReader.parse(new InputSource(is));
orders = handler.getOrders();
}
catch(Exception ex) {
ex.printStackTrace();
}
finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// for(Order or : orders) {
// System.out.println(or.getID() + or.getName() + or.getPhotoName() + or.getPrice() + or.getDetil()+"\n");
// }
return this.orders;
}
}
Order类定义如下:
package com.study.order;
if(orders == null) {
orders = new ArrayList<Order>();
// System.out.println("5-->empty point...");
}
try{
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
XMLReader xmlReader = parser.getXMLReader();
MyHandler handler = new MyHandler();
xmlReader.setContentHandler(handler);
xmlReader.parse(new InputSource(is));
orders = handler.getOrders();
}
catch(Exception ex) {
ex.printStackTrace();
}
finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// for(Order or : orders) {
// System.out.println(or.getID() + or.getName() + or.getPhotoName() + or.getPrice() + or.getDetil()+"\n");
// }
return this.orders;
}
}
Order类定义如下:
package com.study.order;
public class Order {
protected int ID = 0000;
protected String name = null;
protected String photoName = null;
protected double price = 0.0;
protected String detil = null;
public Order() {}
public Order(int idTemp,String nameTemp,String photoNameTemp,double priceTemp,String detilTemp) {
this.ID = idTemp;
this.name = nameTemp;
this.photoName = photoNameTemp;
this.price = priceTemp;
this.detil = detilTemp;
}
public void setID(int idTemp) {
this.ID = idTemp;
}
public int getID() {
return this.ID;
}
public void setName(String nameTemp) {
this.name = nameTemp;
}
public String getName() {
return this.name;
}
public void setPhotoName(String photoNameTemp) {
this.photoName = photoNameTemp;
}
public String getPhotoName() {
return this.photoName;
}
public void setPrice(double priceTemp) {
this.price = priceTemp;
}
public double getPrice() {
return this.price;
}
public void setDetil(String detilTemp) {
this.detil = detilTemp;
}
public String getDetil() {
return this.detil;
}
protected int ID = 0000;
protected String name = null;
protected String photoName = null;
protected double price = 0.0;
protected String detil = null;
public Order() {}
public Order(int idTemp,String nameTemp,String photoNameTemp,double priceTemp,String detilTemp) {
this.ID = idTemp;
this.name = nameTemp;
this.photoName = photoNameTemp;
this.price = priceTemp;
this.detil = detilTemp;
}
public void setID(int idTemp) {
this.ID = idTemp;
}
public int getID() {
return this.ID;
}
public void setName(String nameTemp) {
this.name = nameTemp;
}
public String getName() {
return this.name;
}
public void setPhotoName(String photoNameTemp) {
this.photoName = photoNameTemp;
}
public String getPhotoName() {
return this.photoName;
}
public void setPrice(double priceTemp) {
this.price = priceTemp;
}
public double getPrice() {
return this.price;
}
public void setDetil(String detilTemp) {
this.detil = detilTemp;
}
public String getDetil() {
return this.detil;
}
}
在Activity中代码如下:
package com.study.saxxml;
在Activity中代码如下:
package com.study.saxxml;
import java.util.ArrayList;
import java.util.List;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import com.study.SAX.ReadXML;
import com.study.order.Order;
import com.study.order.Order;
public class MainActivity extends Activity implements OnClickListener {
private Button btn_decode = null;
private TextView txt_show = null;
private Button btn_decode = null;
private TextView txt_show = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.initComponents();
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.initComponents();
}
private void initComponents() {
// btn_decode
this.btn_decode = (Button) findViewById(R.id.btn_001);
this.btn_decode.setOnClickListener(this);
// btn_decode
this.btn_decode = (Button) findViewById(R.id.btn_001);
this.btn_decode.setOnClickListener(this);
// txt_show
this.txt_show = (TextView) findViewById(R.id.txtShow);
}
this.txt_show = (TextView) findViewById(R.id.txtShow);
}
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (arg0.getId() == R.id.btn_001) {
List<Order> orders = new ArrayList<Order>();
ReadXML readxml = new ReadXML(); //创建一个ReadXML对象
readxml.setIs(getResources().openRawResource(R.raw.orders)); //设置对象的输入流
orders = readxml.readFromIs(); //调用对象的readFromIs方法开始数据解析
StringBuffer sb = new StringBuffer();
for (Order or : orders) {
sb.append(or.getID() +" "+ or.getName() + " " +or.getPhotoName()
+ " " +or.getPrice() + " " + or.getDetil() + "\n");
}
this.txt_show.setText(sb);
}
}
}
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (arg0.getId() == R.id.btn_001) {
List<Order> orders = new ArrayList<Order>();
ReadXML readxml = new ReadXML(); //创建一个ReadXML对象
readxml.setIs(getResources().openRawResource(R.raw.orders)); //设置对象的输入流
orders = readxml.readFromIs(); //调用对象的readFromIs方法开始数据解析
StringBuffer sb = new StringBuffer();
for (Order or : orders) {
sb.append(or.getID() +" "+ or.getName() + " " +or.getPhotoName()
+ " " +or.getPrice() + " " + or.getDetil() + "\n");
}
this.txt_show.setText(sb);
}
}