XML Tutorials
  Home arrow XML Tutorials arrow Handling XML Data for Ajax
IBM Developerworks
Codewalker Forums 
  Tutorials  
Database Articles  
Miscellaneous  
Navigation Usability  
PEAR Articles  
Programming Basics  
Server Administration  
XML Tutorials  
  Reviews  
Database Book Reviews  
Linux Book Reviews  
Miscellaneous Reviews  
PHP Book Reviews  
PHP Software Reviews  
Server Admin Reviews  
SQL Tool Reviews  
  Code Gallery  
Content Management Code  
Contest Code  
Counters Code  
Database Code  
Date Time Code  
Discussion Board Code  
Email Code  
File Manipulation Code  
GUI Code  
Link Farm Code  
Miscellaneous Code  
Search Code  
Site Navigation Code  
User Management Code  
Forums Sitemap 
Dedicated Servers  
Download TestComplete 
IBM® developerWorks
Weekly Newsletter 
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
XML TUTORIALS

Handling XML Data for Ajax
By: O'Reilly Media
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 1
    2008-01-03

    Table of Contents:
  • Handling XML Data for Ajax
  • Back on the Client: Mining the XML
  • XML Parsing with JavaScript
  • Populating the Form on a Microsoft Browser
  • Populating the Form on Other Browsers

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
     
    ADVERTISEMENT

    Dell PowerEdge Servers

    Handling XML Data for Ajax
    (Page 1 of 5 )

    This article, the second of a three-part series concerned with XML and JSON for Ajax, explains how to mine and parse XML data for Ajax. It is excerpted from chapter four of the book Ajax on Java, written by Steven Douglas Olson (O'Reilly, 2007; ISBN: 0596101872). Copyright © 2007 O'Reilly Media, Inc. All rights reserved. Used with permission from the publisher. Available from booksellers or direct from O'Reilly Media.

    SAX 

    SAX, the Simple API for XML, provides another way to create an XML document for an Ajax application. It may be faster than JDOM or dom4J, because it doesn't require building a DOM tree for your document. Start by initializing a StringWriter and a StreamResult. Initialize the StreamResultwith theStreamWriter, then get aSAXTransformerFactoryand get aTransformerHandlerfrom that. TheTransformerHandlerallows you to create an XML document by starting a document and appending elements and data to theTransformerHandler. Example 4-4 shows how it works.

    Example 4-4. Using SAX to write out the XML document

    // additional imports for writing XML with SAX
    import java.io.*;
    import org.xml.sax.helpers.AttributesImpl; import javax.xml.transform.sax.SAXTransformerFactory; import javax.xml.transform.sax.TransformerHandler;

    public String createSAXXML(int key) {
        Writer writer = new StringWriter();
        StreamResult streamResult = new StreamResult(writer);

        SAXTransformerFactory transformerFactory =
                (SAXTransformerFactory) SAXTransformerFactory.newInstance();
       
    try{
            String data = null;
            TransformerHandler transformerHandler = 

        transformerFactory.newTransformerHandler();

            transformerHandler.setResult(streamResult);
            // start the document
            transformerHandler.startDocument();
            // list all the attributes for element
            AttributesImpl attr = new AttributesImpl();
            // start writing elements
            // every start tag and end tag has to be defined explicitly
            transformerHandler.startElement(null,null, "converted-values", null);
            transformerHandler.startElement(null,null,"decimal",null);
            data = Integer.toString(key, 10);
            transformerHandler.characters(data.toCharArray(),0,data.length());

            transformerHandler.endElement(null,null,"decimal");

            transformerHandler.startElement(null,null,"hexadecimal",null);
            data = "0x" + Integer.toString(key, 16);
            transformerHandler.characters(data.toCharArray(),0,data.length());

            transformerHandler.endElement(null,null,"hexadecimal");
            transformerHandler.startElement(null,null,"octal",null);
            data = "0" + Integer.toString(key, 8);
            transformerHandler.characters(data.toCharArray(),0,data.length());

            transformerHandler.endElement(null,null,"octal");
            transformerHandler.startElement(null,null,"binary",null);
            data = Integer.toString(key, 2)+"B";
            transformerHandler.characters(data.toCharArray(),0,data.length());

            transformerHandler.endElement(null,null,"binary");
            transformerHandler.startElement(null,null,"hyper",null);
            data = "&0x" +Integer.toString(key, 16);
            transformerHandler.characters(data.toCharArray(),0,data.length());

            transformerHandler.endElement(null,null,"hyper");
            transformerHandler.endElement(null,null, "converted-values");

            transformerHandler.endDocument();
            transformerHandler.setResult(streamResult);
        } catch (Exception e) {
           
    return null;
        }
        return writer.toString(); 
    }

    After callingstartDocument()to begin the document, we must create the elements and add data to them. We create an element by callingstartElement():

      transformerHandler.startElement(null,null,"binary",null)

    The third element is the only element needed to set up the XML tag,<binary>.

    The actualstartElement()method declaration looks like this:

      public void startElement(String uri, String localName, String
      qName, Attributes atts)

    Theuri parameter is used for the namespace, but since this example does not use a namespace, anullis passed in.

    The second parameter,localName, is also used for the namespace and not needed in this example.

    The third parameter,qName, is the qualified name.

    The last parameter,atts, is used when the element has attributes; pass innullif attributes are not used, as in this case.

    To put the data after the element tag, we set aString,data, to the desired value:

      data = Integer.toString(key, 2)+"B";

    Then we convert the data to aCharArrayand pass it into thecharacters()method. The second and third parameters show where processing starts and stops in theCharArray:

      transformerHandler.characters(data.toCharArray(),0,data.length());

    Finally, we terminate the element with a call toendElement():

      transformerHandler.endElement(null,null,"binary");

    Each element is created withstartElement(),characters(), andendElement(). When all of the elements for the documents have been completed, a call toendDocument()is executed and the result is sent to theStreamResultthat was set up at the start of the method:

      transformerHandler.endElement(null,null, "converted-values");
      transformerHandler.endDocument();
      transformerHandler.setResult(streamResult);

    Finally, theStreamResultis converted to aStringby callingtoString()on theStringWriter. TheStreamResultwraps theStringWriterthat was set up at the beginning of this method:

      return writer.toString();

    TheStringcan then be returned to the calling method.

    Using SAX is purportedly a faster and less memory-intensive way to create XML documents than using DOM-based libraries such as JDOM and dom4j. If your testing shows that speed is an issue, or if the SAX API is more natural for your application, you should consider using it.

    There are other ways to create an XML document. For example, the Apache project's Element Construction Set (ECS) allows you to create an XML document, but there is no method to add data to the document at this time, so for this application ECS is not useful.

    More XML Tutorials Articles
    More By O'Reilly Media


       · This article is an excerpt from the book "Ajax on Java," published by O'Reilly. We...
     
     

    Buy this book now. This article is excerpted from chapter four of the book Ajax on Java, written by Steven Douglas Olson (O'Reilly, 2007; ISBN: 0596101872). Check it out today at your favorite bookstore. Buy this book now.

    XML TUTORIALS ARTICLES

    - Creating RSS 2.0 Feeds
    - Using Modules in Your RSS Feed
    - RSS 2.0
    - Querying XML: Use Cases
    - Joins and Query Use with XML
    - Solving Problems by Querying XML
    - Performing Set Operations When Querying XML
    - Querying XML
    - Handling Data for Ajax with JSON
    - Handling XML Data for Ajax
    - XML and JSON for Ajax


     
    Accelerating Trading Partner Performance
     
    Competing on Analytics
     
    Cost Effective Scaling with Virtualization and Coyote Point Systems
     
    Five Checkpoints to Implementing IP Telephony
     
    Hosted Email Security: Staying Ahead of New Threats
     




    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 5 hosted by Hostway