jsp 使用 SAX 读取XML文件代码
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.zzzyk.com/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>
补充:Jsp教程,Java与XML