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.
Next: Back on the Client: Mining the XML >>
More XML Tutorials Articles
More By O'Reilly Media
|
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.
|
|