SAX具体怎么用就不说了,网上搜搜
一大片。
第一步:建立公共抽象类BaseHandler
package com.dc.handler;
import java.io.StringReader;
import java.util.HashMap;
import java.util.Map;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
public abstract class BaseHandler extends DefaultHandler {
//缓存!公共数据的存放类,所有数据都从这里取,一般将它写在Const类中,这里我就不建Const.java了
public static Map hash=new HashMap();//放在Const.java中!
public abstract boolean parse(String xmlString);
public static void parserXml(BaseHandler baseHandler, String xmlString)
throws Exception {
if (xmlString == null || xmlString.length() == 0)
return;
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
XMLReader xmlReader = parser.getXMLReader();
xmlReader.setContentHandler(baseHandler);
//解析文件
// xmlReader.parse(new InputSource(new URL("main.xml").openStream()));//文件
// 创建一个xml字符串
StringReader read = new StringReader(xmlString);
// 创建新的输入源SAX 解析器将使用 InputSource对象来确定如何读取 XML 输入
InputSource source = new InputSource(read);
xmlReader.parse(source);
read.close();
}
public abstract void characters(char[] ch, int start, int length)
throws SAXException;
public abstract void endDocument() throws SAXException;
public abstract void endElement(String uri, String localName, String qName)
throws SAXException;
public abstract void startDocument() throws SAXException;
public abstract void startElement(String uri, String localName, String qName,Attributes attributes) throws SAXException;
}
第二步:实现类
比如,我们要解析一个xml字符串,该字符串可以来自网络。
<students>
<student sn='001'><id>1</id><name>benny</name><age>20</age></student>
<student sn='002'><id>2</id><name>jimmy</name><age>30</age></student>
</students>
解析它:
package com.dc.handler;
import java.util.HashMap;
import java.util.Stack;
import java.util.Vector;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import com.dc.model.Student;
//实现类
public class StudentHandler extends BaseHandler {
private static final String tag="StudentHandler";
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
// TODO Auto-generated method stub
String chars = new String(ch, start, length).trim();
if(chars!=null) {
String tagName = (String)tagStack.peek();//查看栈顶对象而不移除它
Student object=students.lastElement();
// System.out.println("chars="+chars);
if (tagName.equals("id")) {
object.setId(chars);
}else if(tagName.equals("name")){
object.setName(chars);
}else if(tagName.equals("age")){
object.setAge(chars);
}
}
}
@Override
public void endDocument() throws SAXException {
// TODO Auto-generated method stub
// Consts.hash.put("students", students.lastElement());//一个对象
hash.put("students", students);//保存入hash,这里保存的是Vector对象
students=null;//没用了就清掉
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
// TODO Auto-generated method stub
tagStack.pop();//移除栈顶对象并作为此函数的值返回该对象
}
@Override
public boolean parse(String xmlString) {
// TODO Auto-generated method stub
try {
super.parserXml(this, xmlString);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
@Override
public void startDocument() throws SAXException {
// TODO Auto-generated method stub
}
private Stack<String> tagStack = new Stack<String>();
private Vector<Student> students = new Vector<Student>();
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
// TODO Auto-generated method stub
// System.out.println("qName="+qName);
if(qName.equals("student")){
Student object=new Student();
object.setSn(attributes.getValue("sn"));
students.addElement(object);
}
tagStack.push(qName);
}
}
下面是Student的model类:
package com.dc.model;
public class Student {
private String sn;
private String id;
private String name;
private String age;
public String getSn() {
return sn;
}
public void setSn(String sn) {
this.sn = sn;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
第三步:TestCase测试
package com.dc.test;
import java.util.Vector;
import junit.framework.TestCase;
import com.dc.handler.BaseHandler;
import com.dc.handler.StudentHandler;
import com.dc.model.Student;
public class TestStudentHandler extends TestCase {
public void test1(){
String data="<students><student sn='001'><id>1</id><name>benny</name><age>20</age></student><student sn='002'><id>2</id><name>jimmy</name><age>30</age></student></students>";
BaseHandler handler=new StudentHandler();
handler.parse(data);
Vector students=(Vector)BaseHandler.hash.get("students");//hash很重要,所有的东西都在hash中
for(int i=0;i<students.size();i++){
Student student=(Student)students.elementAt(i);
if(student==null){
System.out.println("student is null");
}else{
System.out.println(student.getSn()+":"+student.getId()+":"+student.getName()+":"+student.getAge());
}
}
}
}
打印出:
001:1:benny:20
002:2:jimmy:30
其实这个解析和j2me中jsr172解析xml基本一样。
请看我在j2me中是怎么解析的:
http://gundumw100.iteye.com/admin/blogs/762763
另:奉送j2me中KXML解析xml
http://gundumw100.iteye.com/admin/blogs/760163
Android数据格式解析对象JSON用法
http://www.cnblogs.com/devinzhang/archive/2012/01/09/2317315.html