Home arrow Java arrow Page 4 - Extension Interfaces and SAX
JAVA

Extension Interfaces and SAX


In this conclusion to a three-part article, we look at extension interfaces, XML filters, and more as they relate to the Simple API for XML (SAX). This article is excerpted from chapter four of the book Java and XML, Third Edition, written by Brett McLaughlin and Justin Edelson (O'Reilly, 2006; ISBN: 059610149X). Copyright © 2006 O'Reilly Media, Inc. All rights reserved. Used with permission from the publisher. Available from booksellers or direct from O'Reilly Media.

Author Info:
By: O'Reilly Media
Rating: 3 stars3 stars3 stars3 stars3 stars / 6
July 19, 2007
TABLE OF CONTENTS:
  1. · Extension Interfaces and SAX
  2. · Extension Interfaces
  3. · XMLFilters continued
  4. · XMLWriter

print this article
SEARCH DEVARTICLES

Extension Interfaces and SAX - XMLWriter
(Page 4 of 4 )

Now that you understand how filters work in SAX, I want to introduce you to a specific filter, XMLWriter. This class, as well its subclass, DataWriter, can be downloaded from David Megginsonís site at http://www.megginson.com/Software.

David Megginson shepherded SAX through its early days and has now returned to the fold. David is a SAX guru, and even though he no longer actively works on XMLWriter (or DataWriter ), he has created some incredibly useful classes, and still hosts them on his personal web site.

XMLWriter extends XMLFilterImpl , and DataWriter extends XMLWriter . Both of these filter classes are used to output XML, which may seem a bit at odds with what youíve learned so far about SAX. However, itís not that unusual; you could easily insert statements into a startElement() or characters() callback that fires up a java.io.Writer and outputs to it. In fact, thatís awfully close to what XMLWriter and DataWriter do.

Iím not going to spend a lot of time on this class, because itís not really the way you want to be outputting XML in the general sense; itís much better to use DOM, JDOM, or another XML API if you want mutability. However, the XMLWriter class offers a valuable way to inspect whatís going on in a SAX pipeline. By inserting it between other filters and readers in your pipeline, it can be used to output a snapshot of your data.

For example, in the case where youíre changing namespace URIs, it might be that you want to actually store the XML document with the new namespace URI(be it a modified OíReilly URI, an updated XSL URI, or whatever other use-case you come up with). This is a piece of cake with the XMLWriter class. Since youíve already got SAXTreeViewer using the NamespaceFilter , Iíll use that as an example. First, add import statements for java.io.Writer (for output), and the com.megginson.sax.XMLWriter class. Once thatís in place, youíll need to insert an instance of XMLWriter between the NamespaceFilter and the XMLReader instances; this means output will occur after namespaces have been changed but before the visual events occur:

  public void buildTree(DefaultTreeModel treeModel ,
                      DefaultMutableTreeNode base, String xmlURI)
    throws IOException, SAXException {

    String featureURI = "";
   
XMLReader reader = null;

    try {
     
// Create instances needed for parsing
     
reader = XMLReaderFactory.createXMLReader();
     
JTreeHandler jTreeHandler =
       
new JTreeHandler(treeModel, base);

      XMLWriter writer = new XMLWriter(reader, new FileWriter("snapshot.xml"));
     
NamespaceFilter filter = new NamespaceFilter(writer, 
              "http://www.oreilly.com",
              "http://safari.oreilly.com");

      // Register content handler
     
filter.setContentHandler(jTreeHandler);

      // Register error handler
     
filter.setErrorHandler(jTreeHandler);

      // Register entity resolver
     
filter.setEntityResolver(new SimpleEntityResolver());

      // Register lexical handler
      filter.setProperty("http://xml.org/sax/properties/lexical-handler",
                         jTreeHandler);

      // Turn on validation
      featureURI = "http://xml.org/sax/features/validation";
      filter.setFeature(featureURI, true);

      // Turn on schema validation, as well
      featureURI = "http://apache.org/xml/features/validation/schema";
      filter.setFeature(featureURI, true);

      // Parse
      InputSource inputSource = new InputSource(xmlURI);
      filter.parse(inputSource);
   
} catch (SAXNotRecognizedException e) {
      System.err.println("The parser class " + reader.getClass().getName() +
        " does not recognize the feature URI '" + featureURI + "'");
      System.exit(-1);
    } catch (SAXNotSupportedException e) {
      System.err.println("The parser class " + reader.getClass().getName() +
        " does not support the feature URI '" + featureURI + "'");
      System.exit(-1);
    }
  }

Be sure you set the parent of the NamespaceFilter instance to be the XMLWriter , not the XMLReader . Otherwise, no output will actually occur.

Once youíve got these changes compiled in, run the example. You should get a snapshot.xml file created in the directory from which youíre running the example. Both XMLWriter and DataWriter offer a lot more in terms of methods to output XML, both in full and in part, and you should check out the Javadoc included with the down loaded package.


DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

blog comments powered by Disqus
JAVA ARTICLES

- Java Too Insecure, Says Microsoft Researcher
- Google Beats Oracle in Java Ruling
- Deploying Multiple Java Applets as One
- Deploying Java Applets
- Understanding Deployment Frameworks
- Database Programming in Java Using JDBC
- Extension Interfaces and SAX
- Entities, Handlers and SAX
- Advanced SAX
- Conversions and Java Print Streams
- Formatters and Java Print Streams
- Java Print Streams
- Wildcards, Arrays, and Generics in Java
- Wildcards and Generic Methods in Java
- Finishing the Project: Java Web Development ...

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 

Developer Shed Affiliates

 




© 2003-2017 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials