XML Tutorials
  Home arrow XML Tutorials arrow Page 2 - XML and JSON for Ajax
Moblin
Try It Free
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 
JMSL Numerical Library 
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

XML and JSON for Ajax
By: O'Reilly Media
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 3
    2007-12-27

    Table of Contents:
  • XML and JSON for Ajax
  • Setting Up a Simple XML Document
  • Other Ways to Build the XML Document
  • dom4j

  • 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
     
    Try It Free
     
    ADVERTISEMENT

    Get inside! Sample the range of functionality easily built with JMSL Library for Time Series Data Analysis, Heat Maps, Portfolio Optimization, Monte Carlo Simulation, Stock Price Charting and more. Download Now!

    XML and JSON for Ajax - Setting Up a Simple XML Document


    (Page 2 of 4 )

    Before we delve into the code, we need to make some decisions. We're going to return data using XML, but how should that XML be structured? What should our XML response look like? We don't want anything complex, so well aim to create an XML document that looks like this:

      <converted-values>
          <decimal>97</decimal>
          <hexadecimal>0x61</hexadecimal>
          <octal>0141</octal>
          <hyper>&0x61;</hyper>
          <binary>1100001B</binary>
      </converted-values>

    With this format, the browser can use its document object model (DOM) parser to index and retrieve the data.

    There are many ways to create this XML document. For the sake of simplicity, well first use aStringBuffer to wrap the data with XML tags. Later, we'll look at other ways to create the XML document.

    When I talk about XML formatting, Im referring to the server wrapping the data in XML. The client receives the XML-formatted string in theHTTPResponseand parses it for the individual data fields. The client passes data through the request using eitherHTTPPost()orHTTPGet(). There is no reason for the client to send XML data to the server, because the data is already wrapped in the request as name/value pairs.

    Using a Servlet to Build an XML Document

    Let's start by looking at the servlet code that wraps the data in XML. This servlet is shown in Example4-1.

    Example 4-1. The AjaxResponseServlet

    /*
     
    * Converts a character to hex, decimal, binary, octal, and HTML, then
     
    * wraps each of the fields with XML and sends them back through the response.
     
    */
    package com.AJAXbook.servlet;

    import java.io.IOException;

    import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;

    public class AjaxResponseServlet extends HttpServlet {

        public void doGet(HttpServletRequest req, HttpServletResponse res)
               
    throws ServletException, IOException{
            // key is the parameter passed in from the JavaScript
            // variable named url (see index.html)
            String key = req.getParameter("key");
            StringBuffer returnXML = null;
            if (key != null) {
                // extract the first character from key
                // as an int, then convert that int to a String
                int keyInt = key.charAt(0);
                returnXML = new StringBuffer("\r\n<converted-values>");
                returnXML.append("\r\n<decimal>"+
                               
    Integer.toString(keyInt)+"</decimal>");
                returnXML.append("\r\n<hexadecimal>0x"+
                                Integer.toString(keyInt,16)+"</hexadecimal>");
                returnXML.append("\r\n<octal>0"+
                                Integer.toString(keyInt,8)+"</octal>");
                returnXML.append("\r\n<hyper>&amp;0x"+
                                Integer.toString(keyInt,16)+";</hyper>");
                returnXML.append("\r\n<binary>"+
                                Integer.toString(keyInt,2)+"B</binary>");
                returnXML.append("\r\n</converted-values>");

                // set up the response
                res.setContentType("text/xml");
                res.setHeader("Cache-Control", "no-cache");
                // write out the XML string
                res.getWriter().write(returnXML.toString());
            }
           
    else {
                // if key comes back as a null, return a question mark
                res.setContentType("text/xml");
                res.setHeader("Cache-Control", "no-cache");
                res.getWriter().write("?");
           
    }
        }
    }

    This code is similar to the code from Chapter 3. The only thing that has been added is the code to wrap the data with XML tags:

      returnXML = new StringBuffer("\r\n<converted-values>");
      returnXML.append("\r\n<decimal>"+ 
                       Integer.toString(keyInt)+"</decimal>");
      returnXML.append("\r\n<hexadecimal>0x"+
                       Integer.toString(keyInt,16)+"</hexadecimal>");
      returnXML.append("\r\n<octal>0"+
                       Integer.toString(keyInt,8)+"</octal>");
      returnXML.append("\r\n<hyper>&amp;0x"+
                       Integer.toString(keyInt,16)+";</hyper>");
      returnXML.append("\r\n<binary>"+
                       Integer.toString(keyInt,2)+"B</binary>");
      returnXML.append("\r\n</converted-values>");

    This code simply sets up aStringBuffercalledreturnXML. We then convert the incoming value to decimal, hex, etc.; wrap it with an appropriate XML tag; and append it to the buffer. When we've finished all five conversions and added the closing tag (</converted-values>), we send the response back to the Ajax client usingres.getWriter().write(). We return a question mark (without any XML wrapping) if the key we received wasnull.

    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


    Iron Speed




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