XML Tutorials

  Home arrow XML Tutorials arrow Handling XML Data for Ajax
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 / 4
    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

  •  
     

    SEARCH CODEWALKERS

    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

    blog comments powered by Disqus

    XML TUTORIALS ARTICLES

    - Validation with Document Type Definitions (D...
    - Creating a Well-Formed XML Document
    - Getting to Know XML
    - A Friendly Approach to XML
    - 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

    Developer Shed Affiliates

     



    © 2003-2019 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap