Converting XML to Server-Side Object in JSP

Converting XML to Server-Side Object in JSP Application

In this article, I am going to discuss How to convert XML to Server-Side Object in JSP Application with Examples. Please read our previous article where we discussed How to generate XML from JSP and JavaBeans.

Converting XML to Server-Side Object in JSP

Now to use generated XML in our application, we need to convert the XML to server-side objects and extract the object properties. Here we have to manually parse an XML document and encapsulate it into a JavaBeans component. There are two interfaces for parsing:

  1. Simple API for XML (SAX)
  2. Document Object Model (DOM)
SAX (Simple API for XML)

SAX is not a parser; it is a simple API for XML. It is an interface that is implemented by many different XML parsers. The main advantage of SAX is that it is lightweight and fast because it is an event-based API which means that it directly reports parsing events to the application using callbacks. So, the applications implement different handlers to deals with the events like handling events in GUI.

Converting XML to Server-Side Object in JSP Application

Example

In this example, we are creating a demo program to read an XML file with a SAX parser. Here user.xml file contains XML attributes along with XML elements. Then we are creating User.java model class whose instances will be populated using the SAX parser. Then create a BUserParserHandler.java class by extending DefaultParser. UsersXmlParser.java file is a SAX parser to read the XML file. Then TestSaxParser.java will test whether our handler is actually working.

user.xml
<?xml version="1.0" encoding="UTF-8"?>
<users>
    <user id="100">
        <firstname>Tom</firstname>
        <lastname>Hanks</lastname>
    </user>
    <user id="101">
        <firstname>Lokesh</firstname>
        <lastname>Gupta</lastname>
    </user>
</users>
User.java
public class User {
 // XML attribute id
 private int id;
 // XML element fisrtName
 private String firstName;
 // XML element lastName
 private String lastName;

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getFirstName() {
  return firstName;
 }

 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }

 public String getLastName() {
  return lastName;
 }

 public void setLastName(String lastName) {
  this.lastName = lastName;
 }

 @Override
 public String toString() {
  return this.id + ":" + this.firstName + ":" + this.lastName;
 }
}
UserParserHandler.java
import java.util.ArrayList;
import java.util.Stack;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class UserParserHandler extends DefaultHandler {
 // This is the list which shall be populated while parsing the XML.
 private ArrayList userList = new ArrayList();

 // As we read any XML element we will push that in this stack
 private Stack elementStack = new Stack();

 // As we complete one user block in XML, we will push the User instance in
 // userList
 private Stack objectStack = new Stack();

 public void startDocument() throws SAXException {
  // System.out.println("start of the document : ");
 }

 public void endDocument() throws SAXException {
  // System.out.println("end of the document document : ");
 }

 public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException
    {
        //Push it in element stack
        this.elementStack.push(qName);
 
        //If this is start of 'user' element then prepare a new User instance and push it in object stack
        if ("user".equals(qName))
        {
            //New User instance
            User user = new User();
 
            //Set all required attributes in any XML element here itself
            if(attributes != null && attributes.getLength() == 1)
            {
                user.setId(Integer.parseInt(attributes.getValue(0)));
            }
            this.objectStack.push(user);
        }
    }

 public void endElement(String uri, String localName, String qName) throws SAXException {
  // Remove last added element
  this.elementStack.pop();

  // User instance has been constructed so pop it from object stack and push in
  // userList
  if ("user".equals(qName)) {
   User object = this.objectStack.pop();
   this.userList.add(object);
  }
 }

 /**
  * This will be called everytime parser encounter a value node
  */
 public void characters(char[] ch, int start, int length) throws SAXException {
  String value = new String(ch, start, length).trim();

  if (value.length() == 0) {
   return; // ignore white space
  }

  // handle the value based on to which element it belongs
  if ("firstName".equals(currentElement())) {
   User user = (User) this.objectStack.peek();
   user.setFirstName(value);
  } else if ("lastName".equals(currentElement())) {
   User user = (User) this.objectStack.peek();
   user.setLastName(value);
  }
 }

 /**
  * Utility method for getting the current element in processing
  */
 private String currentElement() {
  return this.elementStack.peek();
 }

 // Accessor for userList object
 public ArrayList getUsers() {
  return userList;
 }
}
UsersXmlParser.java
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;

public class UsersXmlParser {
 public ArrayList parseXml(InputStream in)
    {
        //Create a empty link of users initially
        ArrayList<user> users = new ArrayList</user><user>();
        try
        {
            //Create default handler instance
            UserParserHandler handler = new UserParserHandler();
 
            //Create parser from factory
            XMLReader parser = XMLReaderFactory.createXMLReader();
 
            //Register handler with parser
            parser.setContentHandler(handler);
 
            //Create an input source from the XML input stream
            InputSource source = new InputSource(in);
 
            //parse the document
            parser.parse(source);
 
            //populate the parsed users list in above created empty list; You can return from here also.
            users = handler.getUsers();
 
        } catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
 
        }
        return users;
    }
}
TestSaxParser.java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
 
public class TestSaxParser
{
    public static void main(String[] args) throws FileNotFoundException
    {
        //Locate the file
        File xmlFile = new File("D:/temp/users.xml");
 
        //Create the parser instance
        UsersXmlParser parser = new UsersXmlParser();
 
        //Parse the file
        ArrayList users = parser.parseXml(new FileInputStream(xmlFile));
    }
}
Output

Check your output in the specified folder

How to convert XML to Server-Side Object in JSP Application with Examples

Load your XML file into the browser:

How to convert XML to Server-Side Object in JSP Application

DOM (Document Object Model)

Dom is a platform-neutral and language-neutral interface for accessing and updating documents. An XML document can be accessed by DOM through a tree structure composed of element nodes and text nodes. We can easily modify or delete the content and also, we can create new elements. The main advantage of DOM is that it is simpler to program as compared to SAX.

Example

In this example, user.xml is the XML file that contains attributes along with the XML elements. In the DomExample.java file, we are importing all the XML-related packages, and then creating a document builder. Then create a document from a file and then extract the root element and examine the attributes and sub-elements. Here, we are traversing the tree produced by the XML file using the Document.getDocumentElement() file.

user.xml
<?xml version="1.0" encoding="UTF-8"?>
<users>
    <user >
    	<id>100</id>
        <firstname>Tom</firstname>
        <lastname>Hanks</lastname>
    </user>
    <user>
    	<id>101</id>
        <firstname>Lokesh</firstname>
        <lastname>Gupta</lastname>
    </user>
</users>
DomExample.java
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class DomExample {

 public static void main(String args[]) {
  try {

   File users = new File("user.xml");
   DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
   DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
   Document doc = dBuilder.parse(users);
   doc.getDocumentElement().normalize();

   System.out.println("root of xml file" + doc.getDocumentElement().getNodeName());
   NodeList nodes = doc.getElementsByTagName("users");
   System.out.println("==========================");

   for (int k = 0; k < nodes.getLength(); k++) {
    Node node = nodes.item(k);

    if (node.getNodeType() == Node.ELEMENT_NODE) {
     Element element = (Element) node;
     System.out.println("User ID: " + getValue("id", element));
     System.out.println("User Firstname: " + getValue("firstname", element));
     System.out.println("User Lastname: " + getValue("lastname", element));
    }
   }
  } catch (Exception ex) {
   ex.printStackTrace();
  }
 }

 private static String getValue(String tag, Element element) {
  NodeList nodes = element.getElementsByTagName(tag).item(0).getChildNodes();
  Node node = (Node) nodes.item(0);
  return node.getNodeValue();
 }
}
Output

Generating XML from JSP and JavaBeans with Examples

In the next article, I am going to discuss JavaBeans in JSP Application. Here, in this article, I try to explain How to convert XML to Server-Side Objects in JSP Applications and I hope you enjoy this How to convert XML to Server-Side Objects in JSP Applications with Examples.

Leave a Reply

Your email address will not be published.