XML Tutorials

  Home arrow XML Tutorials arrow Page 2 - XML and JSON for Ajax
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 / 4
    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

  •  
     

    SEARCH CODEWALKERS

    TOOLS YOU CAN USE

    advertisement

    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

    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


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