SAX 是事件驅動的 XML 解析方式,它不會把整份文件塞進記憶體,而是邊讀邊觸發回呼。這個範例示範如何搭配一個 Stack,在解析過程中隨時知道「目前正身處哪個標籤」。
[java]
package com.jiangqq.xml.sax;
import java.io.File;
import java.util.Stack;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class SaxTest02 {
public static void main(String[] args) throws Exception, SAXException {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
parser.parse(new File("student.xml"), new myHandler());
}
}
class myHandler extends DefaultHandler {
private Stack<String> stack = new Stack<String>();
private String name;
private String gender;
private String age;
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
stack.push(qName);
for (int i = 0; i < attributes.getLength(); i++) {
String attrName = attributes.getQName(i);
String attrValue = attributes.getValue(i);
System.out.println(attrName + " = " + attrValue);
}
}
@Override
public void characters(char[] ch, int start, int end) throws SAXException {
String tag = stack.peek();
if ("姓名".equals(tag)) {
name = new String(ch, start, end);
} else if ("性別".equals(tag)) {
gender = new String(ch, start, end);
} else if ("年齡".equals(tag)) {
age = new String(ch, start, end);
}
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
// 該元素解析完畢,從堆疊彈出
stack.pop();
if ("學生".equals(qName)) {
System.out.println("姓名 :" + name);
System.out.println("性別 :" + gender);
System.out.println("年齡 :" + age);
System.out.println(" ");
}
}
}
<?xml version="1.0" encoding="UTF-8"?>
<學生名冊>
<學生 學號="1">
<姓名>張三</姓名>
<性別>男</性別>
<年齡>21</年齡>
</學生>
<學生 學號="2">
<姓名>李四</姓名>
<性別>女</性別>
<年齡>20</年齡>
</學生>
<學生 學號="3">
<姓名>王五</姓名>
<性別>男</性別>
<年齡>23</年齡>
</學生>
</學生名冊>
學號 = 1 姓名 :張三 性別 :男 年齡 :21 學號 = 2 姓名 :李四 性別 :女 年齡 :20 學號 = 3 姓名 :王五 性別 :男 年齡 :23
SAX 是「流式」的,解析器不會告訴你上一層是誰。把 qName 在 startElement 時推入、在 endElement 時彈出,peek() 拿到的就是當前所處的標籤,等於用一個堆疊手工重建了文件樹的層級關係。這個小技巧在處理只有少數欄位、又不想引入 DOM 的場景時特別好用。