jsp教程 使用 SAX 讀取XML檔案代碼
<%@ page contentType="text/html; charset=gb2312" language="java" import="java.sql.*" errorPage="" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.111cn.net/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
</head>
<body>
<%
SAX
package test.xml;
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.helpers.DefaultHandler;
/**
* 使用 SAX 讀取XML檔案。
*
*/
public class TestXMLBySAX extends DefaultHandler {
java.util.Stack tags = new java.util.Stack();
public static void main(String args[]) {
long lasting = System.currentTimeMillis();
System.out.println("Read By SAX");
try {
// 構建工廠
SAXParserFactory sf = SAXParserFactory.newInstance();
SAXParser sp = sf.newSAXParser();
// 構建處理類,每個標籤都會讓處理類進行解析
TestXMLBySAX reader = new TestXMLBySAX();
// 解析
sp.parse(new InputSource("text.xml"), reader);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("已耗用時間:" + (System.currentTimeMillis() - lasting) + "毫秒");
}
@Override
public void characters(char ch[], int start, int length) throws SAXException {
String tag = (String) tags.peek();
if (tag.equals("NO")) {
System.out.println("車牌號碼:" + length + new String(ch, start, length));
}
if (tag.equals("ADDR")) {
System.out.println("地址:" + length + new String(ch, start, length));
}
}
@SuppressWarnings("unchecked")
@Override
public void startElement(String uri, String localName, String qName, Attributes attrs) {
tags.push(qName);
}
}
%>
</body>
</html>
xml檔案:
<?xml version="1.0" encoding="GB2312"?>
<RESULT>
<VALUE>
<NO>A1234</NO>
<ADDR>四川省XX縣XX鎮XX路X段XX號</ADDR>
</VALUE>
<VALUE>
<NO>B1234</NO>
<ADDR>四川省XX市XX鄉XX村XX組</ADDR>
</VALUE>
</RESULT>