␡
- A Refresher
- The Servlet Class: TransformData
- Helper Class: URLDecoder
- Main Transformation Class: FormDataToXML
- Conclusion
Like this article? We recommend
Main Transformation Class: FormDataToXML
The primary purpose of this class is to parse a Query String of URLEncoded name value pairs, and output an XML document. Make sure that you have downloaded and configured the java dom libraries from w3c and the Xerces xml processor libraries from the Apache project Web site.
/** * FormDataToXML * * @Author Jasmit Singh Kochhar * * @Date Created 08/2001 * * @Purpose This class is used to transform an HTML form data * into an XML string * */ import java.util.Vector; import java.util.Hashtable; import java.util.StringTokenizer; import java.util.Enumeration; import java.lang.StringBuffer; import java.net.URLEncoder; import java.io.*; import org.w3c.dom.*; import org.apache.xerces.dom.DocumentImpl; import org.apache.xerces.dom.DOMImplementationImpl; import org.w3c.dom.Document; import org.apache.xml.serialize.OutputFormat; import org.apache.xml.serialize.Serializer; import org.apache.xml.serialize.SerializerFactory; import org.apache.xml.serialize.XMLSerializer; /* custom helper class */ import URLDecoder; // for decoding URL strings public class FormDataToXML { Hashtable formElements; Vector orderElements; int maxNum; /** * Constructor used to initialize: * formElements - Hashtable that contains the name value posted values * orderElements - Vector with the order of the elements * maxNum - Maximum number of variables in the posted form * */ public FormDataToXML() { formElements = new Hashtable(25); orderElements = new Vector(25,25); maxNum = -1; } /** * Method: setItemOrder * * @Purpose The method adds the items to a vector based on the * order indicated in the HTML form to be used for the * construction of the XML document. Also the name of * the variables without the index is added to orderElements. * @param String s is name of the posted variable * */ public void setItemOrder(String s) { int length = s.length(); int aNameInt = -1; int i; String aName = null; for (i = 0; i < length; i += 1) { // Continue searching the strings till a non digit char is found if (! Character.isDigit(s.charAt(i))){ aName = s.substring(0,i); aNameInt = (Integer.valueOf(aName)).intValue(); break; } } if (aName != null){ String aValue = s.substring(i); if (aNameInt > maxNum) { maxNum = aNameInt; orderElements.setSize(maxNum+1); } // Use the integer part as the index for the element // in the vector and the rest as the value for xml string orderElements.setElementAt(aValue,aNameInt); } } /** * Method: parseQueryString * * @Purpose The method parses the URL encoded string of data. * The name value pairs are added to the hashtable * formElements and the order of xml variables * is populated in the orderElements vector. * * @param String htmlFormData takes the Query String of urlencoded * name value pairs * */ public void parseQueryString(String htmlFormData) { // iterate for all "&" in the Query string StringTokenizer stAmpersand = new StringTokenizer(htmlFormData,"&"); while ( stAmpersand.hasMoreTokens() ) { String anItem = stAmpersand.nextToken(); if ( anItem != null ) { // iterate for the "=" in the Name=Value pair StringTokenizer stEqual = new StringTokenizer(anItem,"="); if ( stEqual.hasMoreTokens() ) { String aName = URLDecoder.decode(stEqual.nextToken()); if ( aName != null && aName.length() > 0 && stEqual.hasMoreTokens() ) { // add the variable to orderElements vector this.setItemOrder(aName); String aValue = null; if ( stEqual.hasMoreTokens() ) aValue = URLDecoder.decode(stEqual.nextToken()); // add the Name, value pair to the formElements hashtable formElements.put(aName,aValue); } } } } } /** * Method: toXML * * @Purpose The method returns the xml data string for the html * form data submitted by the user. * @param String htmlformData * @return String XML String representation of the posted data * */ public String toXML(String htmlFormData) { StringBuffer output=new StringBuffer(100); try{ int i; String varName = null; String aName = null; String aValue = null; // parse the Query String/ URLEncoded data submitted by the HTML form parseQueryString(htmlFormData); // Create the XML DOM Object Document doc= new DocumentImpl(); //Create the root node for the document Element root = doc.createElement("function"); doc.appendChild( root ); // Set the root node as the current Node Node curNode = doc.getFirstChild(); // Iterate to the value of the variable maxNum and process // each variable as indicated by the HTML form data into the // the corresponding nodes of the XML document for (i=0; i<= maxNum; i++) { varName = (String) orderElements.elementAt(i); if (varName != null){ aName = new String (i+varName); aValue = (String) formElements.get(aName); // Parse the varible for the / which indicates the level StringTokenizer stSlash = new StringTokenizer(varName,"/"); while ( stSlash.hasMoreTokens() ) { String anItem = stSlash.nextToken(); System.out.println("item is" + anItem); if ( anItem == null ) // get the root node curNode = doc.getFirstChild(); else if (anItem.equals("..")) // get the parent of the current Node curNode = curNode.getParentNode(); else { // Create the element to the current Node Element item = doc.createElement(anItem); curNode.appendChild( item ); curNode = item; } } // while // For the final leaf node get the value submitted in the // HTML form curNode.appendChild( doc.createTextNode(aValue ) ); } // if } // for // Serialize the output as a string OutputFormat format = new OutputFormat( doc ); //Serialize DOM StringWriter stringOut = new StringWriter(); //Writer will be a String XMLSerializer serial = new XMLSerializer( stringOut, format ); serial.asDOMSerializer(); // As a DOM Serializer serial.serialize( doc.getDocumentElement() ); output.append(stringOut.toString()); } catch ( Exception ex ) { ex.printStackTrace(); } return output.toString(); } /** * * Method main * * @Purpose Used to test different URL encoded strings * */ public static void main (String args []) { String htmlString = "1%2Fname=ADD_USER&2..%2Fparameters%2Ffirstname=Jasmit&3..%2Fcontactinfo%2Faddress=1234+some+addr"; String xmlString; FormDataToXML h = new FormDataToXML(); xmlString=h.toXML(htmlString); System.out.println(xmlString); } }