Pages

Tuesday, 18 December 2012

Simple JSP application to Read and Write XML Content

Simple JSP application to Read and Write XML Content

Let's take a case of simple news reader and writer application.

simple news.xml

<root_news>
<news id='1'>
    <date>1-1-11</date>
    <title>Stars at BBC Sports Awards</title>
    <description>Stars at BBC Sports Awards
Kate, the Duchess of Cambridge walks out to present Lord Sebastian Coe with the Lifetime Achievement Award during the BBC Sports Personality of the Year Awards 2012 in London, Sunday Dec. 16, 2012. (Photo: AP)</description>
</news>
<news id='2'>
    <date>2-2-12</date>
    <title>Cricket: 5 Legendary Umpires</title>
    <description>Cricket: 5 Legendary Umpires</description>
</news>
<news id='3'>
    <date>3-3-13</date>
    <title>PICS: Fun Christmas Activities</title>
    <description>Participants in the annual "Santa Speedo Run" leave the starting line in Boston
Participants in the annual "Santa Speedo Run," a charity race through the streets of the Back Bay neighborhood of Boston, Massachusetts leave the starting line.
</description>
</news>
<news id='4'>
    <date>4-4-14</date>
    <title>Apple in Talks with Foursquare Over Maps</title>
    <description>Apple Inc is in early discussions with Foursquare Labs Inc to integrate local data into the company's mapping application, the Wall Street Journal reported, citing people familiar with the talks.</description>
</news>
</root_news>


Our index.jsp displays one news section from xml file and has option to edit and update the news date,title and description. We are skipping validation for now to make it simpler.

index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<%@page import="javax.xml.transform.Source"%>
<%@page import="javax.xml.transform.dom.DOMSource"%>
<%@page import="javax.xml.transform.Result"%>
<%@page import="javax.xml.transform.stream.StreamResult"%>
<%@page import="javax.xml.transform.TransformerFactory"%>
<%@page import="javax.xml.transform.Transformer"%>
<%@page import="java.io.FileWriter"%>
<%@page import="java.io.OutputStream"%>
<%@page import="java.io.StringWriter"%>
<%@page import="java.io.File"%>
<%@page import="java.io.BufferedWriter"%>
<%@page import="java.io.OutputStreamWriter"%>
<%@page import="java.io.FileOutputStream"%><html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>News</title>
<%@page import="org.w3c.dom.Document"%>
<%@page import="java.io.InputStream"%>
<%@page import="javax.xml.parsers.DocumentBuilderFactory"%>
<%@page import="javax.xml.parsers.DocumentBuilder"%>
<%@page import="javax.xml.parsers.ParserConfigurationException"%>
<%@page import="org.xml.sax.SAXException"%>
<%@page import="org.w3c.dom.NodeList"%>
<%@page import="org.w3c.dom.Node"%>
<%@page import="org.w3c.dom.Element"%>
</head>
<body>

    <%
    Document doc = null;
    InputStream path = null;
    try {
        path = getServletContext().getResourceAsStream("news.xml");
        //File fXmlFile = new File(path);
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        doc = dBuilder.parse(path);
        doc.getDocumentElement().normalize();           
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    }
   
    NodeList nodeList = doc.getElementsByTagName("news");
   
    String newsIdParam = "1";
   
    String date = "";
    String title = "";
    String desc = "";
   
    Element dateElement = null;
    Element titleElement = null;
    Element descElement = null;
   
    for(int i=0; i<nodeList.getLength();i++){
        Node node = nodeList.item(i);
        if(node.getNodeType() == Node.ELEMENT_NODE){
            Element element = (Element)node;
            String newsId = element.getAttribute("id");
            if(newsId.equals(newsIdParam)){
                NodeList childNodeList = element.getElementsByTagName("date");
                if(childNodeList !=null && childNodeList.getLength() == 1){
                    Node childNode = childNodeList.item(0);
                    if(childNode.getNodeType() == Node.ELEMENT_NODE){
                        dateElement = (Element) childNode;
                        date = dateElement.getFirstChild().getNodeValue();
                    }                   
                }
                NodeList titleNodeList = element.getElementsByTagName("title");
                if(titleNodeList !=null && titleNodeList.getLength() == 1){
                    Node childNode = titleNodeList.item(0);
                    if(childNode.getNodeType() == Node.ELEMENT_NODE){
                        titleElement = (Element) childNode;
                        title = titleElement.getFirstChild().getNodeValue();
                    }                   
                }
                NodeList descNodeList = element.getElementsByTagName("description");
                if(descNodeList !=null && descNodeList.getLength() == 1){
                    Node childNode = descNodeList.item(0);
                    if(childNode.getNodeType() == Node.ELEMENT_NODE){
                        descElement = (Element) childNode;
                        desc = titleElement.getFirstChild().getNodeValue();
                    }                   
                }
            }   
        }
    }

    %>
    <form action="updateNews.jsp">
    <table>
        <tr>
            <td> Date :</td>
            <td><input type="text" id="date" name="date" value="<%=date %>"></input>
            </td>
        </tr>
        <tr>
            <td> Title :</td>
            <td><input type="text" id="title" name="title" value="<%=title %>"></input></td>
        </tr>
        <tr>
            <td> Description :</td>
            <td>    <textarea cols="50" rows="2" id="desc" name="desc"><%=desc %></textarea></td>
        </tr>
        <tr>
            <td> </td>
            <td><input type="submit" name="save" title="Update" value="Update"/></td>
        </tr>
    </table>
        <input type="hidden" name="id" value="1">
    </form>
</body>
</html>

Our updateNews.jsp will be called on click of update button in index.jsp page.
It will read parameters passed from index.jsp page, updates the xml node with new values,open xml file to write,and write the new content.

<%@page import="javax.xml.transform.OutputKeys"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<%@page import="javax.xml.transform.Source"%>
<%@page import="javax.xml.transform.dom.DOMSource"%>
<%@page import="javax.xml.transform.Result"%>
<%@page import="javax.xml.transform.stream.StreamResult"%>
<%@page import="javax.xml.transform.TransformerFactory"%>
<%@page import="javax.xml.transform.Transformer"%>
<%@page import="java.io.FileWriter"%>
<%@page import="java.io.OutputStream"%>
<%@page import="java.io.StringWriter"%>
<%@page import="java.io.File"%>
<%@page import="java.io.BufferedWriter"%>
<%@page import="java.io.OutputStreamWriter"%>
<%@page import="java.io.FileOutputStream"%>
<%@page import="org.w3c.dom.Document"%>
<%@page import="java.io.InputStream"%>
<%@page import="javax.xml.parsers.DocumentBuilderFactory"%>
<%@page import="javax.xml.parsers.DocumentBuilder"%>
<%@page import="javax.xml.parsers.ParserConfigurationException"%>
<%@page import="org.xml.sax.SAXException"%>
<%@page import="org.w3c.dom.NodeList"%>
<%@page import="org.w3c.dom.Node"%>
<%@page import="org.w3c.dom.Element"%>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Update News</title>
</head>
<body>

    <% String date=request.getParameter("date");
    String title=request.getParameter("title");
    String desc=request.getParameter("desc");
    String id = request.getParameter("id");
    out.println(date);
    out.println(title);
    out.println(desc);
    out.println(id);
   
    Document doc = null;
    InputStream path = null;
    try {
        path = getServletContext().getResourceAsStream("news.xml");
        //File fXmlFile = new File(path);
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        doc = dBuilder.parse(path);
        doc.getDocumentElement().normalize();           
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    }
   
    NodeList nodeList = doc.getElementsByTagName("news");
   
    String newsIdParam = "1";
   
    Element dateElement = null;
    Element titleElement = null;
    Element descElement = null;
   
    for(int i=0; i<nodeList.getLength();i++){
        Node node = nodeList.item(i);
        if(node.getNodeType() == Node.ELEMENT_NODE){
            Element element = (Element)node;
            String newsId = element.getAttribute("id");
            if(newsId.equals(id)){
                NodeList childNodeList = element.getElementsByTagName("date");
                if(childNodeList !=null && childNodeList.getLength() == 1){
                    Node childNode = childNodeList.item(0);
                    if(childNode.getNodeType() == Node.ELEMENT_NODE){
                        dateElement = (Element) childNode;
                    }                   
                }
                NodeList titleNodeList = element.getElementsByTagName("title");
                if(titleNodeList !=null && titleNodeList.getLength() == 1){
                    Node childNode = titleNodeList.item(0);
                    if(childNode.getNodeType() == Node.ELEMENT_NODE){
                        titleElement = (Element) childNode;
                    }                   
                }
                NodeList descNodeList = element.getElementsByTagName("description");
                if(descNodeList !=null && descNodeList.getLength() == 1){
                    Node childNode = descNodeList.item(0);
                    if(childNode.getNodeType() == Node.ELEMENT_NODE){
                        descElement = (Element) childNode;
                    }                   
                }
            }   
        }
    }
   
    // updating values
    dateElement.getFirstChild().setNodeValue(date);
    titleElement.getFirstChild().setNodeValue(title);
    descElement.getFirstChild().setNodeValue(desc);
   
    doc.normalize();
    TransformerFactory tFactory = TransformerFactory.newInstance();
    Transformer tFormer = tFactory.newTransformer();
    tFormer.setOutputProperty(OutputKeys.INDENT, "yes");
     //create string from xml tree
     StringWriter sw = new StringWriter();
     StreamResult result = new StreamResult(sw);
     DOMSource source = new DOMSource(doc);
     tFormer.transform(source, result);
     String xmlString = sw.toString();
     System.out.println(xmlString);
     System.out.println(result.getWriter().toString());
   
     File file = new File("D:\\Project\\news.xml");
     FileWriter fileWriter = new FileWriter(file);
     BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);

     bufferedWriter.write(result.getWriter().toString());

     bufferedWriter.flush();
     bufferedWriter.close();   

    %>
</body>
</html>

Thats all ... :-)



No comments:

Post a Comment