Subscribe

RSS Feed (xml)

Powered By

Skin Design:
Free Blogger Skins

Powered by Blogger

Monday, December 3, 2007

java code for JSP and SAX

<%@ page import="javax.xml.parsers.SAXParserFactory,
javax.xml.parsers.SAXParser,
com.java2s.MyHandler"%>


JSP and SAX

<%
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
MyHandler myHandler = new MyHandler(out);

parser.parse("http://localhost:8080/chapter10/people.xml",
myHandler);
%>




package com.java2s;

import java.io.IOException;
import javax.servlet.jsp.JspWriter;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class MyHandler extends DefaultHandler
{
private int stepCount, totalAge;
private JspWriter out;
private boolean insideAgeElement;

public MyHandler(JspWriter out)
{
this.out = out;
}

public void startDocument() throws SAXException
{
try
{
out.write(++stepCount + ". Start of document
");
}
catch (IOException e)
{
throw new SAXException(e);
}
} // end of startDocument()

public void endDocument() throws SAXException
{
try
{
out.write(++stepCount + ". End of document

");
out.write("The total of all ages in the XML document is "
+ totalAge + "
");
}
catch (IOException e)
{
throw new SAXException(e);
}
} // end of endDocument()

public void startElement(String namespaceURI, String localName,
String qName, Attributes attrs)
throws SAXException
{
if ( qName.equals("age"))
{
insideAgeElement = true;
}

try
{
out.write(++stepCount + ". Start of element: " + qName + "");

int numberOfAttributes = attrs.getLength();

if ( numberOfAttributes > 0 )
{
out.write(". Attributes:

    ");
    } // end of if ()
    else
    out.write("
    ");

    for ( int i=0; i {
    out.write("
  • " + attrs.getQName(i) + " = "
    + attrs.getValue(i) + "
  • ");
    } // end of for ()

    if ( numberOfAttributes > 0 )
    {
    out.write("
");
}
}
catch (IOException e)
{
throw new SAXException(e);
}
} // end of startElement()

public void endElement(String namespaceURI, String localName, String qName)
throws SAXException
{
if ( qName.equals("age") )
{
insideAgeElement = false;
}

try
{
out.write(++stepCount + ". End of element " + qName + "
");
}
catch (IOException e)
{
throw new SAXException(e);
} // end of try-catch

} // end of endElement()

public void characters(char[] chars, int start, int length) throws SAXException
{
String content = new String(chars, start, length);

if ( insideAgeElement )
{
int age = Integer.parseInt(content);
totalAge += age;
}

try
{
out.write(++stepCount + ". Character content = ");

if ( length > 0 )
out.write("" + content + "
");
}
catch (IOException e)
{
throw new SAXException(e);
} // end of try-catch

} // end of characters()
} // end of class MyHandler

No comments: