1. Home >
  2. Apps >
  3. Groups >

xml and java

Question asked by viswasknit in #Java on Sep 11, 2009
viswasknit
viswasknit · Sep 11, 2009
Rank D2 - MASTER
I want to use xml as a database in my web project...
But I don't know how can I use this.........

Please help me.................. Posted in: #Java
viswasknit
viswasknit · Sep 11, 2009
Rank D2 - MASTER
here i want give detail of my problem...


A xml file book.xml




cobol
roy


java
herbert


c++
robert


coldfusion
allaire


xml unleashed
morrison


jrun
allaire



Now i want a jsp page to take data of book.xml file..............


I use tomcat 6.018 as a server...............
sookie
sookie · Sep 12, 2009
Rank C1 - EXPERT
JSP Part, I am leaving to you, if get stuck anywhere, feel free to ask. Below is how to read .xml file in Java file.

Pre-requisite: Knowledge of Parsers -SAX and DOM.

Taking your Books.xml example only
Books.xml




cobol
roy



java
herbert



c++
robert



coldfusion
allaire



xml unleashed
morrison



Now how to retrieve this data in Java program. There are two approaches of doing so:
1. Using SAX [Simple API for XML]

package myjava;

import java.io.File;
import java.io.IOException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class XMLReaderUsingSAX {

    public static void main(String[] args) throws IOException {
        String xmlFile = "I:/Books.xml";
        System.out.print("XML file name:" + xmlFile);
        XMLReaderUsingSAX detail = new XMLReaderUsingSAX(xmlFile);
    }

    public XMLReaderUsingSAX(String str) {
        try {
            File file = new File(str);
            /*checks if the file exists */
            if (file.exists()) {
                SAXParserFactory parserFact = SAXParserFactory.newInstance();
                SAXParser parser = parserFact.newSAXParser();
                System.out.println("XML Data: ");
                DefaultHandler dHandler = new DefaultHandler() {

                    boolean title;
                    boolean author;
                    boolean mail;

                    public void startElement(String uri, String localName, String element_name, Attributes attributes) throws SAXException {
                        if (element_name.equals("title")) {
                            title = true;
                        }
                        if (element_name.equals("author")) {
                            author = true;
                        }
                    }

                    public void characters(char[] ch, int start, int len) throws SAXException {
                        String str = new String(ch, start, len);
                        if (title) {
                            System.out.println("Title:" + str);
                            title = false;
                        }
                        if (author) {
                            System.out.println("Author:" + str);
                            author = false;
                        }
                    }
                };

                parser.parse(str, dHandler);
            } else {
                System.out.println("File not found!");
            }
        } catch (Exception e) {
            System.out.println("XML File hasn't any elements");
            e.printStackTrace();
        }
    }
}
Output:
XML file name:I:/Books.xmlXML Data:
Title:cobol
Author:roy
Title:java
Author:herbert
Title:c++
Author:robert
Title:coldfusion
Author:allaire
Title:xml unleashed
Author:morrison
In above Java class, SAXParser class parses the XML file using parse() method. The characters() method prints data until value of element in startElement() is true

Characters(char[] ch, int start, int len) method retrieves identification of character data. The Parser calls this method and to report every character data encountered . If any error occurs it throws the SAXException. This method takes the following parameters:

  • ch: This is the characters of XML document.
  • start: This is staring position in an array.
  • len: This is the number of characters to read from an array.

2. Using DOM[Document Object Model]
package myjava;

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 XMLReaderUsingDOM {

    public static void main(String argv[]) {

        try {
            File file = new File("I:/Books.xml");
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = (Document) db.parse(file);
            doc.getDocumentElement().normalize();
            NodeList nodeList = doc.getElementsByTagName("book");


            for (int s = 0; s < nodeList.getLength(); s++) {

                Node firstNode = nodeList.item(s);

                if (firstNode.getNodeType() == Node.ELEMENT_NODE) {

                    Element firstElement = (Element) firstNode;
                    NodeList fstNmElmntLst = firstElement.getElementsByTagName("title");
                    Element fstNmElmnt = (Element) fstNmElmntLst.item(0);
                    NodeList fstNm = fstNmElmnt.getChildNodes();
                    System.out.println("Title: " + ((Node) fstNm.item(0)).getNodeValue());
                    NodeList lstNmElmntLst = firstElement.getElementsByTagName("author");
                    Element lstNmElmnt = (Element) lstNmElmntLst.item(0);
                    NodeList lstNm = lstNmElmnt.getChildNodes();
                    System.out.println("Author: " + ((Node) lstNm.item(0)).getNodeValue());
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
Output:
Title: cobol
Author: roy
Title: java
Author: herbert
Title: c++
Author: robert
Title: coldfusion
Author: allaire
Title: xml unleashed
Author: morrison
In case 2, "book" is kind of hard-coded.

For more information about SAX and DOM, check following
SAX API
DOM API

Let me know, if you need any more details. Thanks !

You must log-in or sign-up to reply to this post.

Click to Log-In or Sign-Up