CrazyEngineers
  • xml and java

    viswasknit

    Member

    Updated: Oct 26, 2024
    Views: 938
    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..................
    0
    Replies
Howdy guest!
Dear guest, you must be logged-in to participate on CrazyEngineers. We would love to have you as a member of our community. Consider creating an account or login.
Replies
  • viswasknit

    MemberSep 11, 2009

    here i want give detail of my problem...


    A xml file book.xml

    <?xml version="1.0" ?>
    <books>
    <book>
    <title>cobol</title>
    <author>roy</author>
    </book>
    <book>
    <title>java</title>
    <author>herbert</author>
    </book>
    <book>
    <title>c++</title>
    <author>robert</author>
    </book>
    <book>
    <title>coldfusion</title>
    <author>allaire</author>
    </book>
    <book>
    <title>xml unleashed</title>
    <author>morrison</author>
    </book>
    <book>
    <title>jrun</title>
    <author>allaire</author>
    </book>
    </books>

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


    I use tomcat 6.018 as a server...............
    Are you sure? This action cannot be undone.
    Cancel
  • sookie

    MemberSep 12, 2009

    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
    <?xml version = "1.0" ?>
    <Books>

    <book>
    <title>cobol</title>
    <author>roy</author>
    </book>

    <book>
    <title>java</title>
    <author>herbert</author>
    </book>

    <book>
    <title>c++</title>
    <author>robert</author>
    </book>

    <book>
    <title>coldfusion</title>
    <author>allaire</author>
    </book>

    <book>
    <title>xml unleashed</title>
    <author>morrison</author>
    </book>


    </Books>
    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
    #-Link-Snipped-#
    #-Link-Snipped-#

    Let me know, if you need any more details. Thanks !
    Are you sure? This action cannot be undone.
    Cancel
Home Channels Search Login Register