Thursday, March 29, 2007


XML Parsing using SAX Parser

Write a java class that extends DefaultHandler with following methods:

import org.xml.sax.*;
import org.xml.sax.helpers.*;

public class MyParser extends DefaultHandler {
public void startDocument( ) throws SAXException
public void endDocument( ) throws SAXException
public void startElement( String namespaceURI,
String localName,
String qName,
Attributes attr ) throws SAXException {
System.out.println( “Start element : “+localName);
for ( int i = 0; i <>
System.out.println( " ATTRIBUTE: " +
attr.getLocalName(i) +
" VALUE: " +
attr.getValue(i) );

public void endElement( String namespaceURI,
String localName,
String qName ) throws SAXException {

System.out.println( “End element : “+localName);
public void characters( char[] ch, int start, int length )
throws SAXException {

String val=null;
val = new String(ch, start, length);
System.out.println(“Characters :“+val);


Use above in your program as follows :
try {
// Create SAX 2 parser...
XMLReader xr = XMLReaderFactory.createXMLReader();
// Set the ContentHandler...
xr.setContentHandler( new QueryParser() );
// Parse the file...
InputSource is = new InputSource(new StringReader(Test.getXMLQueryString()));
xr.parse( is );

}catch ( Exception e ) {

Xslt for webRowSet to html

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="" xmlns:wrs="" version="1.0">
<xsl:template match="/">
<h2>Query Results</h2>
<h3> Total Count : <xsl:value-of select="count(wrs:webRowSet/wrs:data/wrs:currentRow)"/> </h3>
<table border="1">
<tr bgcolor="lightgray">
<xsl:for-each select="wrs:webRowSet/wrs:metadata/wrs:column-definition">
<th><xsl:value-of select="wrs:column-label"/></th>

<!-- fill in the table rows -->

<xsl:for-each select="wrs:webRowSet/wrs:data/wrs:currentRow">
<xsl:for-each select="wrs:columnValue">
<td><xsl:value-of select="."/></td>

Other important xslt:

If you have a xml like :
To print each value in a comma separated list :
<xsl:template match="/list">
<xsl:value-of select="val[1]"/>,
<xsl:value-of select="val[2]"/>,
<xsl:value-of select="val[3]"/>,

No comments: