请先将xerces.jar文件放入web应用程序的WEB-INF/lib目录中,再编写处理xml文件的处理器如下:
package example;
import java.io.*;
import java.util.Hashtable;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
public class SAXHandler extends DefaultHandler
{
private Hashtable table = new Hashtable();
private String currentElement = null;
private String currentValue = null;
public void setTable(Hashtable table)
{
this.table = table;
}
public Hashtable getTable()
{
return table;
}
public void startElement(String nspaceURI, String localName, String qName, Attributes atts) throws SAXException {
// System.out.println("Starting element: " + localName);
currentElement = localName;
}
public void characters(char[] ch, int start, int length) throws SAXException
{
currentValue = new String(ch, start, length);
}
public void endElement(String namespaceURI, String localName, String qualifiedName) throws SAXException {
// System.out.println("Ending element: " + localName);
if (currentElement.equals(localName))
table.put(currentElement, currentValue); //将元素名和内容放入一个Hashtable
}
}
用下面的jsp代码测试:
<%@ page contentType="text/html; charset=GBK" %>
<HTML>
<HEAD>
<TITLE>剖析XML文件web.xml</TITLE>
</HEAD>
<BODY>
<%@ page import="org.xml.sax.*" %>
<%@ page import="org.xml.sax.helpers.XMLReaderFactory" %>
<%@ page import="example.SAXHandler" %>
<%@ page import="java.util.*" %>
<% String fi=getServletContext().getRealPath("/")+"dir1\\dir6\\ex.xml";
XMLReader parser = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");
SAXHandler handler = new SAXHandler();
parser.setContentHandler(handler);
parser.parse(fi);
Hashtable hashTable = handler.getTable();
Enumeration e=hashTable.keys();
while(e.hasMoreElements()){
String key=(String)e.nextElement();
out.println(key+": "+hashTable.get(key)+"<br>");
}
%>
ex.xml文件如下:
<?xml version="1.0" encoding="GB2312" standalone="no" ?>
<!DOCTYPE booklist [
<!ELEMENT booklist (book)+>
<!ELEMENT book (书名,定价,读者交流信箱)>
<!ELEMENT 书名 (#PCDATA)>
<!ELEMENT 定价 (#PCDATA)>
<!ELEMENT 读者交流信箱 (#PCDATA)>
<!ENTITY QA-email "zz3zcwb@sina.com">
]>
<booklist>
<book>
<书名>一起玩OfficeXP</书名>
<定价>580元</定价>
<读者交流信箱>&QA-email;</读者交流信箱>
</book>
</booklist>
posted on 2006-01-12 12:59
zjw_albert 阅读(117)
评论(0) 编辑 收藏