当前页面: 开发资料首页 → Java 专题 → 在jsp中使用SAX
在jsp中使用SAX
摘要: 在jsp中使用SAX
</td>
</tr>
<tr>
<td height="35" valign="top" class="ArticleTeitle">
请先将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" %>
<head>
剖析XML文件web.xml
</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)+"
");
}
%>
<table width="675" height="26" border="0">
<tr>
<td width="357">ex.xml文件如下:
<?xml version="1.0" encoding="GB2312" standalone="no" ?>
booklist [
]>
<书名>一起玩OfficeXP书名>
<定价>580元定价>
<读者交流信箱>&QA-email;读者交流信箱>
</td>
<td width="308">
</td>
</tr>
</table>
function TempSave(ElementID)
{
CommentsPersistDiv.setAttribute("CommentContent",document.getElementById(ElementID).value);
CommentsPersistDiv.save("CommentXMLStore");
}
function Restore(ElementID)
{
CommentsPersistDiv.load("CommentXMLStore");
document.getElementById(ElementID).value=CommentsPersistDiv.getAttribute("CommentContent");
}
</td>
</tr>
<tr>
↑返回目录
前一篇: 简单购物车
后一篇: 用JSP创建可重用的图形背景