Jsp code
<!--
Sams Teach Yourself JavaServer Pages in 21 Days (Paperback)
by Steven Holzner (Author), Steve Holzner (Author)
# Publisher: Sams; 1st edition (September 19, 2002)
# Language: English
# ISBN-10: 0672324490
# ISBN-13: 978-0672324499
-->
<%@ page import="org.xml.sax.*, org.xml.sax.helpers.DefaultHandler, javax.xml.parsers.*, java.io.*" %>
<%!
javax.servlet.jsp.JspWriter localOut;
public class parser extends DefaultHandler
{
String indent = "";
void parse(String name)
{
DefaultHandler handler = this;
SAXParserFactory factory = SAXParserFactory.newInstance();
try {
SAXParser saxParser = factory.newSAXParser();
saxParser.parse(new File(name), handler);
} catch (Throwable t) {}
}
public void startDocument() throws SAXException
{
try{
localOut.println("<?xml version=\"1.0\" encoding=\""+"UTF-8" + "\"?><BR>");
}
catch(java.io.IOException e){}
}
public void endDocument() throws SAXException
{
}
public void startElement(String namespaceURI, String localName, String qualifiedName, Attributes attrs)
throws SAXException
{
try{
String elementName = localName;
if ("".equals(elementName)) {
elementName = qualifiedName;
}
localOut.println(indent + "<" + elementName);
if (attrs != null) {
for (int i = 0; i < attrs.getLength(); i++) {
String attributeName = attrs.getLocalName(i);
if ("".equals(attributeName)) attributeName = attrs.getQName(i);
localOut.println(attributeName + "=");
localOut.println("\"" + attrs.getValue(i) + "\"");
}
}
localOut.println("><BR>");
indent += " ";
}
catch(java.io.IOException e){}
}
public void endElement(String namespaceURI, String localName, String qualifiedName)
throws SAXException
{
try{
String elementName = localName;
if ("".equals(elementName)) {
elementName = qualifiedName;
}
indent = indent.substring(0, indent.length() - 24);
localOut.println(indent + "</" + elementName + ">");
localOut.println("<BR>");
}
catch(java.io.IOException e){}
}
public void characters(char buf[], int offset, int len)
throws SAXException
{
try{
String s = new String(buf, offset, len);
if (!s.trim().equals("")) {
localOut.println(indent + " " + s);
localOut.println("<BR>");
}
}
catch(java.io.IOException e){}
}
}
%>
<HTML>
<HEAD>
<TITLE>Parsing an XML Document with SAX</TITLE>
</HEAD>
<BODY>
<H1>Parsing an XML Document with SAX</H1>
<%
localOut = out;
parser p = new parser();
p.parse(application.getRealPath("/") + "test.xml");
%>
</BODY>
</HTML>
XML document
<a>
<b>
</b>
</a>
Download: JSPSAXParser.zip( 2 k)