KickJava   Java API By Example, From Geeks To Geeks.

Java > Java SE, EE, ME > org > xml > sax > helpers > DefaultHandler

org.xml.sax.helpers
Class DefaultHandler

java.lang.Object
  extended by org.xml.sax.helpers.DefaultHandler
All Implemented Interfaces:
ContentHandler, DTDHandler, EntityResolver, ErrorHandler
Direct Known Subclasses:
DefaultHandler2
See Also:
Top Examples, Source Code, HandlerBase

public void characters(char[] ch,
                       int start,
                       int length)
                throws SAXException
See Also:
ContentHandler
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


[676]Process characters from SAX handler
By nguyenvtri { at } yahoo { dot } com on 2004/03/02 07:01:31  Rate
    public void characters ( char buf [  ] , int offset, int len )  
     //throws SAXException 
      {  
       System.out.println ( "---- >  > COME IN---- >  > " ) ; 
       String s = new String ( buf, offset, len ) ; 
       System.out.println ( "length=" + len ) ; 
       System.out.println ( "--OUT: " + s ) ; 
       if  ( s.indexOf ( "\n" )   <  0 && s.length (  )   >  0 )   {  
         this.m_sCurrentNodeValue = s; 
         System.out.println ( "---IN: " + s ) ; 
        }  
       System.out.println ( " <  < ----COME OUT <  < ----" ) ;       
      } 


public DefaultHandler()
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public void endDocument()
                 throws SAXException
See Also:
ContentHandler
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public void endElement(String uri,
                       String localName,
                       String qName)
                throws SAXException
See Also:
ContentHandler
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public void endPrefixMapping(String prefix)
                      throws SAXException
See Also:
ContentHandler
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public void error(SAXParseException e)
           throws SAXException
See Also:
ErrorHandler.warning(org.xml.sax.SAXParseException)
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public void fatalError(SAXParseException e)
                throws SAXException
See Also:
ErrorHandler
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public void ignorableWhitespace(char[] ch,
                                int start,
                                int length)
                         throws SAXException
See Also:
ContentHandler
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public void notationDecl(String name,
                         String publicId,
                         String systemId)
                  throws SAXException
See Also:
DTDHandler
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public void processingInstruction(String target,
                                  String data)
                           throws SAXException
See Also:
ContentHandler
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public InputSource resolveEntity(String publicId,
                                 String systemId)
                          throws IOException,
                                 SAXException
See Also:
EntityResolver
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public void setDocumentLocator(Locator locator)
See Also:
ContentHandler
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public void skippedEntity(String name)
                   throws SAXException
See Also:
ContentHandler.processingInstruction(java.lang.String, java.lang.String)
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public void startDocument()
                   throws SAXException
See Also:
ContentHandler
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public void startElement(String uri,
                         String localName,
                         String qName,
                         Attributes attributes)
                  throws SAXException
See Also:
ContentHandler
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


[1581]SAX helper class captures individual element and attribute values
By Anonymous on 2005/11/04 20:23:08  Rate
/** 
 This abstract helper class extends the SAX2  < b > DefaultHandler < /b >  class and 
 interprets XML document information at a higher level than is reported 
 through the usual  < b > ContentHandler < /b >  interface. It captures individual 
 element and attribute values, and reports them to the derived class through 
 two abstract methods,  { @link #element element }  and 
  { @link #attribute attribute } . 
 */
 
 public abstract class SAXInterpreter 
     extends DefaultHandler 
  {  
     /** 
     The interpreter will call this method when it has detected an XML 
     element with a single value. 
  
  
     @param name The element name 
     @param value The element value as raw character data 
     @param path A stack of strings built from the document element, 
         with the last string on the stack being the parent of this element. 
     */
 
     public abstract void element  ( String name, String value, Stack path ) ; 
  
  
     /** 
     The interpreter will call this method when it has detected an XML 
     attribute. 
  
  
     @param name The attribute name 
     @param value The attribute value as raw character data 
     @param path A stack of strings built from the document element, 
         with the last string on the stack being the containing element. 
     */
 
     public abstract void attribute  ( String name, String value, Stack path ) ; 
  
  
     /** 
     Push the element name onto the  { @link #path }  stack. 
     Read out all attributes and call the  { @link #attribute }  handler. 
     Reset the character buffer  { @link #elementValue } . 
     */
 
     public void startElement  ( String URI, String localName, 
             String qName, Attributes attributes )  
         throws SAXException 
      {  
         path.push  ( qName ) ; 
  
  
         int length = attributes.getLength  (  ) ; 
         for  ( int a = 0; a  <  length; ++a )  
             attribute  ( attributes.getQName  ( a ) , 
                 attributes.getValue  ( a ) , path ) ; 
  
  
         elementValue = new StringBuffer  (  ) ; 
      }  
  
  
     /** 
     Accummulate character data if the  { @link #elementValue }  buffer is enabled. 
     */
 
     public void characters  ( char [  ]  chars, int start, int length )  
         throws SAXException 
      {  
         if  ( elementValue != null )  
             elementValue.append  ( chars, start, length ) ; 
      }  
  
  
     /** 
     Pop this element off the stack  ( so that it's not reported as its own 
     parent ) . If the  { @link #elementValue }  buffer is enabled  ( even if it's 
     empty ) , call the  { @link #element element }  handler. 
     */
 
     public void endElement  ( String URI, String localName, String qName )  
         throws SAXException 
      {  
         path.pop  (  ) ; 
  
  
         // If elementValue is null, this is a mixed or complex element. 
         // If it's "", the element is empty. 
         if  ( elementValue != null )  
             element  ( qName, elementValue.toString  (  ) , path ) ; 
  
  
         elementValue = null; 
      }  
  
  
     /** 
     Helper to convert a path stack into a readable/parsable XPath string. 
     */
 
     protected static String XPath  ( Stack path )  
      {  
         StringBuffer result = new StringBuffer  ( "//" ) ; 
  
  
         Iterator each = path.iterator  (  ) ; 
         while  ( each.hasNext  (  )  )  
             result.append  (  ( String )  each.next  (  )  )  
                   .append  ( '/' ) ; 
  
  
         return result.toString  (  ) ; 
      }  
  
  
     /** 
     Get a deep copy of the current path anytime during parsing. 
     */
 
     protected Collection getPath  (  )  
      {  
         return new Vector  ( path ) ; 
      }  
  
  
     /** 
     Stack of parent element names. 
     */
 
     private Stack path = new Stack  (  ) ; 
  
  
     /** 
     Buffer for element character data. 
     */
 
     private StringBuffer elementValue; 
  }  
  
  
 


public void startPrefixMapping(String prefix,
                               String uri)
                        throws SAXException
See Also:
ContentHandler
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public void unparsedEntityDecl(String name,
                               String publicId,
                               String systemId,
                               String notationName)
                        throws SAXException
See Also:
DTDHandler
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public void warning(SAXParseException e)
             throws SAXException
See Also:
ErrorHandler
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


[1577]Use SAX to re-generate XML file
By Anonymous on 2005/11/04 20:23:08  Rate
import java.io.*; 
 import javax.xml.parsers.*; 
 import org.xml.sax.*; 
 import org.xml.sax.helpers.*; 
  
  
 /** 
 This application class accepts a source XML filename and uses SAX to parse 
 the file. It echoes the contents with some modifications, restoring 
 line breaks and a simple pattern of indenting child elements. 
  
  
 One major limitation: we gather character data for elements in a single 
 buffer, so mixed-content documents will lose a lot of data! This works 
 best with data-centric documents where elements either have single values 
 or child elements, but not both. 
 */
 
 public class PrettyPrinter 
     extends DefaultHandler 
  {  
     /** 
     Gets a SAX parser factory, and sets the  < b > namespace-prefixes < /b >  
     property to true, to assure that we'll echo prefix mappings as 
     normal attributes. Parses the 
     file whose name is passed on the command line. 
     */
 
     public static void main  ( String [  ]  args )  
      {  
         try 
          {  
             SAXParserFactory factory = SAXParserFactory.newInstance  (  ) ; 
             try 
              {  
                 factory.setFeature 
                      ( "http://xml.org/sax/features/namespace-prefixes", true ) ; 
              }  
             catch  ( SAXException ex )  
              {  
                 ex.printStackTrace  (  ) ; 
              }  
  
  
             parser = factory.newSAXParser  (  ) ; 
             if  ( args.length == 0 )  
                 parser.parse  ( System.in, new PrettyPrinter  (  )  ) ; 
             else 
                 parser.parse  ( new File  ( args [ 0 ]  ) , new PrettyPrinter  (  )  ) ; 
          }  
         catch  ( ParserConfigurationException ex )  
          {  
             ex.printStackTrace  ( System.err ) ; 
          }  
         catch  ( SAXException ex2 )  
          {  
             ex2.printStackTrace  ( System.err ) ; 
          }  
         catch  ( IOException ex3 )  
          {  
             ex3.printStackTrace  ( System.err ) ; 
          }  
      }  
  
  
     /** 
     Prints the XML declaration. 
     */
 
     public void startDocument  (  )  
         throws SAXException 
      {  
         System.out.println  ( " < ?xml version=\"1.0\" encoding=\"UTF-8\" ? > " ) ; 
      }  
  
  
     /** 
     Prints a blank line at the end of the reformatted document. 
     */
 
     public void endDocument  (  )  throws SAXException 
      {  
         System.out.println  (  ) ; 
      }  
  
  
     /** 
     Writes the start tag for the element. 
     Attributes are written out, one to a text line. Starts gathering 
     character data for the element. 
     */
 
     public void startElement 
              ( String URI, String name, String qName, Attributes attributes )  
         throws SAXException 
      {  
         StringBuffer output = new StringBuffer  (  ) ; 
  
  
         output.append  ( endLine )  
               .append  ( indent )  
               .append  ( ' < ' )  
               .append  ( qName ) ; 
  
  
         int length = attributes.getLength  (  ) ; 
         for  ( int a = 0; a  <  length; ++a )  
             output.append  ( endLine )  
                   .append  ( indent )  
                   .append  ( standardIndent )  
                   .append  ( attributes.getQName  ( a )  )  
                   .append  ( "=\"" )  
                   .append  ( attributes.getValue  ( a )  )  
                   .append  ( '\"' ) ; 
  
  
         if  ( length  >  0 )  
             output.append  ( endLine )  
                   .append  ( indent ) ; 
  
  
         output.append  ( ' > ' ) ; 
  
  
         System.out.print  ( output.toString  (  )  ) ; 
  
  
         indent += standardIndent; 
         currentValue = new StringBuffer  (  ) ; 
      }  
  
  
     /** 
     Checks the  { @link #currentValue }  buffer to gather element content. 
     Writes this out if it is available. Writes the element end tag. 
     */
 
     public void endElement  ( String URI, String name, String qName )  
         throws SAXException 
      {  
         indent = indent.substring 
              ( 0, indent.length  (  )  - standardIndent.length  (  )  ) ; 
  
  
         if  ( currentValue == null )  
          {  
             currentValue = new StringBuffer  (  ) ; 
             currentValue.append  ( endLine )  
                         .append  ( indent ) ; 
          }  
  
  
         currentValue.append  ( " < /" )  
                     .append  ( qName )  
                     .append  ( ' > ' ) ; 
  
  
         System.out.print  ( currentValue.toString  (  )  ) ; 
         currentValue = null; 
      }  
  
  
     /** 
     When the  { @link #currentValue }  buffer is enabled, appends character 
     data into it, to be gathered when the element end tag is encountered. 
     */
 
     public void characters  ( char [  ]  chars, int start, int length )  
         throws SAXException 
      {  
         if  ( currentValue != null )  
             currentValue.append  ( escape  ( chars, start, length )  ) ; 
      }  
  
  
     /** 
     Filter to pass strings to output, escaping  < b > < < /b >  and  < b > & < /b >  
     characters to &lt; and &amp; respectively. 
     */
 
     private static String escape  ( char [  ]  chars, int start, int length )  
      {  
         StringBuffer result = new StringBuffer  (  ) ; 
         for  ( int c = start; c  <  start + length; ++c )  
             if  ( chars [ c ]  == ' < ' )  
                 result.append  ( "<" ) ; 
             else if  ( chars [ c ]  == '&' )  
                 result.append  ( "&" ) ; 
             else 
                 result.append  ( chars [ c ]  ) ; 
  
  
         return result.toString  (  ) ; 
      }  
  
  
     /** 
     This whitespace string is expanded and collapsed to manage the output 
     indenting. 
     */
 
     private String indent = ""; 
  
  
     /** 
     A buffer for character data. It is "enabled" in 
      { @link #startElement startElement }  by being initialized to a 
     new  < b > StringBuffer < /b > , and then read and reset to 
      < code > null < /code >  in  { @link #endElement endElement } . 
     */
 
     private StringBuffer currentValue = null; 
  
  
     static SAXParser parser; 
     private static final String endLine = "\r\n"; 
     private static final String standardIndent = " "; 
  }  
  
  
 


[1580]Create a SAX parser that can validate against DTDs or Schema
By Anonymous on 2005/11/04 20:23:08  Rate
import javax.xml.parsers.*; 
 import org.xml.sax.*; 
 import org.xml.sax.helpers.*; 
  
  
 /** 
 A simple application class that creates a validating SAX parser and 
 validates a document whose name is passed on the command line. 
 */
 
  
  
 public class SAXValidator 
     extends DefaultHandler 
  {  
     /** 
     Report the warning to the console. 
     */
 
     public void warning  ( SAXParseException ex )  
         throws SAXException 
      {  
         System.out.println  
              ( "Warning at Line " + locator.getLineNumber  (  )  + ":" ) ; 
         System.out.println  ( " " + ex.getMessage  (  )  ) ; 
      }  
      
     /** 
     Report the error to the console. 
     */
 
     public void error  ( SAXParseException ex )  
         throws SAXException 
      {  
         System.out.println  
              ( "Error at Line " + locator.getLineNumber  (  )  + ":" ) ; 
         System.out.println  ( " " + ex.getMessage  (  )  ) ; 
      }  
      
     /** 
     Grab a reference to the parser's document locator for later use in 
     error and warning reports. 
     */
 
     public void setDocumentLocator  ( Locator locator )  
      {  
         this.locator = locator; 
      }  
      
     /** 
     Create a SAX parser that can validate against DTDs or Schema. 
     This is accomplished by delegation to  
      { @link #getSchemaValidatingSAXParser getSchemaValidatingSAXParser } . 
     Parse the document whose name is the first command-line argument. 
     */
 
     public static void main  ( String [  ]  args )  
      {  
         try 
          {  
             if  ( args.length == 0 )  
              {  
                 System.out.println  ( "Usage: " + 
                     "java SAXValidator  < XML filename > " ) ; 
                 System.exit  ( -1 ) ; 
              }  
              
             SAXParser parser = getSchemaValidatingSAXParser  (  ) ; 
             parser.parse  ( new java.io.File  ( args [ 0 ]  ) , new SAXValidator  (  )  ) ; 
          }  
         catch  ( Exception ex )  
          {  
             ex.printStackTrace  (  ) ; 
          }  
      }  
      
     /** 
     Gets a SAX parser with JAXP 1.2 features turned on 
     to allow validation of a parsed document using XML Schema. 
     */
 
     public static SAXParser getSchemaValidatingSAXParser  (  )  
      {  
         SAXParser result = null; 
  
  
         try 
          {  
             SAXParserFactory factory = SAXParserFactory.newInstance  (  ) ; 
             factory.setValidating  ( true ) ; 
             factory.setFeature  
                  ( "http://xml.org/sax/features/namespaces", true ) ; 
              
             result = factory.newSAXParser  (  ) ; 
             result.setProperty  
                  ( "http://java.sun.com/xml/jaxp/properties/schemaLanguage",  
                     "http://www.w3.org/2001/XMLSchema" ) ; 
          }  
         catch  ( Exception ex )  
          {  
             System.out.println  ( "This parser apparently can't " + 
                 "validate against XML Schema." ) ; 
             System.out.println  ( "   ( " + ex.getMessage  (  )  + " ) " ) ; 
          }  
          
         return result; 
      }  
      
     /** 
     This references the most recently reported document locator. 
     */
 
     private Locator locator; 
  }  
  
  
 

Popular Tags