Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 5 of 5

Thread: XML Parsel problems

  1. #1
    Junior Member adrian.tudor's Avatar
    Join Date
    Dec 2012
    Location
    Bucharest, Romania
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default XML Parsel problems

    Can anyone help me with this code? I can't take some tags from xml file.

    Here is the code.

    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 XMLParser {
     
        public void getAllUserNames(String fileName) {
            try {
                DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                DocumentBuilder db = dbf.newDocumentBuilder();
                File file = new File(fileName);
                if (file.exists()) {
                    Document doc = db.parse(file);
                    Element docEle = doc.getDocumentElement();
     
                    // Print root element of the document
                    System.out.println("Root element of the document: "
                            + docEle.getNodeName());
     
     
                    //Printare detalii carte.
                     NodeList studentList1 = docEle.getElementsByTagName("bookDetails");
     
                                            Node node1 = studentList1.item(0);
     
                            if (node1.getNodeType() == Node.ELEMENT_NODE) {
     
                                System.out
                                        .println("BookDetails");
     
                                Element e = (Element) node1;
                                NodeList nodeList1 = e.getElementsByTagName("bookName");
                                System.out.println("bookName: "
                                        + nodeList1.item(0).getChildNodes().item(0)
                                                .getNodeValue());
                                nodeList1 = e.getElementsByTagName("authorName");
                                System.out.println("authorName: "
                                        + nodeList1.item(0).getChildNodes().item(0)
                                                .getNodeValue());
                                nodeList1 = e.getElementsByTagName("ISBN");
                                System.out.println("ISBN: "
                                        + nodeList1.item(0).getChildNodes().item(0)
                                                .getNodeValue());
     
                            }
                    //termnare detalii carte.
     
     
     
                    //{Printare capitole
     
     
                    NodeList studentList = docEle.getElementsByTagName("chapter");
     
                    // total capitole
                    System.out
                            .println("Total capitole: " + studentList.getLength());
     
                    if (studentList != null && studentList.getLength() > 0) {
                        for (int i = 0; i < studentList.getLength(); i++) {
     
                            Node node = studentList.item(i);
     
                            if (node.getNodeType() == Node.ELEMENT_NODE) {
     
                                System.out
                                        .println("=====================");
     
                                Element e = (Element) node;
                                NodeList nodeList = e.getElementsByTagName("chapterName");
                                System.out.println("Nume capitol: "
                                        + nodeList.item(0).getChildNodes().item(0)
                                                .getNodeValue());
     
     
                                //Pentru fiecare sentence dintr-un capitol.
                                NodeList studentList2 = docEle.getElementsByTagName("chapter"); 
     
                                if (studentList2 != null && studentList2.getLength() > 0) {
                                //paragrafe 
     
     
                                for (int k = 0; k < studentList2.getLength(); k++) {
     
                                    Node node2 = studentList2.item(k);
     
                                    if (node.getNodeType() == Node.ELEMENT_NODE) {
                                         nodeList = e.getElementsByTagName("Paragrap");
                                            System.out.println("Paragrap: "
                                              + nodeList.item(k).getChildNodes().item(0)
                                                .getNodeValue());
                                    }
                                }
     
                            } else {
                        System.exit(1);
                    }
                        }
                        }
                    } else {
                        System.exit(1);
                    }
                }
            } catch (Exception e) {
                System.out.println(e);
            }
        }
        public static void main(String[] args) {
     
            XMLParser parser = new XMLParser();
            parser.getAllUserNames("d:\\book1.xml");
        }
    }

    Here is the input file

    <?xml version="1.0" encoding="UTF-8" ?>
     <book>
     	<bookDetails>
    		<bookName>Pheonix Order</bookName>
      		<authorName>J. K. Rolings</authorName>
      		<ISBN>2012314123</ISBN>
      	</bookDetails>
     <chapter>
     	<chapterName>Capitol 1 Inceput</chapterName>
    		<Paragrap>A fost o data.</Paragrap>
    		<Paragrap>Ca niciodata.</Paragrap>
    		<Paragrap>Ca daca nu ar fi.</Paragrap>
    		<Paragrap>Nu s-ar mai povestii.</Paragrap>
    		<Paragrap>sfarsit.</Paragrap>
    		<Paragrap>2A fost o data.</Paragrap>
    		<Paragrap>2Ca niciodata.</Paragrap>
    <Paragrap>2Ca daca nu ar fi.</Paragrap>
    		<Paragrap>2Nu s-ar mai povestii.</Paragrap>
    		<Paragrap>2sfarsit.</Paragrap>
     </chapter>
     <chapter>
      	<chapterName>Capitol 2 Continuare</chapterName>
    		<Paragrap>De mult a fost o data.</Paragrap>
    <Paragrap>De ca niciodata.</Paragrap>
    <Paragrap>De daca nu ar fi.</Paragrap>
    		<Paragrap>De nu s-ar mai povestii.</Paragrap>
    		<Paragrap>De in sfarsit.</Paragrap>
     </chapter>
     <chapter>
      	<chapterName>Capitol 3 Sfarsit</chapterName>
      		<Paragrap>In mult a fost o data.</Paragrap>
    <Paragrap>In ca niciodata.</Paragrap>
    <Paragrap>In daca nu ar fi.</Paragrap>
    <Paragrap>In nu s-ar mai povestii.</Paragrap>
    		<Paragrap>In in sfarsit.</Paragrap>
     </chapter>
     </book>

    And output is

    Root element of the document: book
    BookDetails
    bookName: Pheonix Order
    authorName: J. K. Rolings
    ISBN: 2012314123
    Total capitole: 3
    =====================
    Nume capitol: Capitol 1 Inceput
    Paragrap: A fost o data.
    Paragrap: Ca niciodata.
    Paragrap: Ca daca nu ar fi.
    =====================
    Nume capitol: Capitol 2 Continuare
    Paragrap: De mult a fost o data.
    Paragrap: De ca niciodata.
    Paragrap: De daca nu ar fi.
    =====================
    Nume capitol: Capitol 3 Sfarsit
    Paragrap: In mult a fost o data.
    Paragrap: In ca niciodata.
    Paragrap: In daca nu ar fi.

    But i can't select all paragraphs, can anyone tell me how to fix it?

    Edit:

    NodeList studentList2 = docEle.getElementsByTagName("chapter"); 
        for (int k = 0; k < studentList2.getLength(); k++)

    Here is the problem but if i write like this
    NodeList studentList2 = docEle.getElementsByTagName("Paragrap");

    it give me java.lang.NullPointerException , how can i solve it?
    VISTA = Virus Inside Switch to Apple
    UNIX - Where there is a shell, there's a way.


  2. #2
    Super Moderator curmudgeon's Avatar
    Join Date
    Aug 2012
    Posts
    1,130
    My Mood
    Cynical
    Thanks
    64
    Thanked 140 Times in 135 Posts

    Default Re: XML Parsel problems

    I would first rename your variables to make them more self-commenting. I will show you what I mean, but of course my variable names will be in English while yours will be in whatever language you are familiar with. I would then use the same chapter Node to get the chapterName item as well as the paragraph data. I would then extract the text from the Node using getTextContent(). For example:

                NodeList chapterList = docEle.getElementsByTagName("chapter");
                System.out.println("Total capitole: " + chapterList.getLength());
     
                if (chapterList != null && chapterList.getLength() > 0) {
                   for (int i = 0; i < chapterList.getLength(); i++) {
     
                      Node chapterNode = chapterList.item(i);
     
                      if (chapterNode.getNodeType() == Node.ELEMENT_NODE) {
     
                         // .... code deleted for sake of brevity
     
                         Element chapterElement = (Element) chapterNode;
                         NodeList chapterNameNodeList = chapterElement.getElementsByTagName("chapterName");
     
                         // .... code deleted for sake of brevity
     
                         NodeList paragraphList = chapterElement.getElementsByTagName("Paragrap");
                         for (int j = 0; j < paragraphList.getLength(); j++) {
                            Node paragraphNode = paragraphList.item(j);
                            if (paragraphNode.getNodeType() == Node.ELEMENT_NODE) {
                               System.out.println("Paragrap: " + paragraphNode.getTextContent());
                            }
                         }

  3. #3
    Junior Member adrian.tudor's Avatar
    Join Date
    Dec 2012
    Location
    Bucharest, Romania
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: XML Parsel problems

    Sorry for crapy variables name, didn't have time to rename it and make it more visible and precised.
    Thanks for your time, but isn't what i need.

    Your code just print all paragraphs, here is the output.
    Root element of the document: book
    BookDetails
    bookName: Pheonix Order
    authorName: J. K. Rolings
    ISBN: 2012314123
    Total capitole: 3
    Paragrap: A fost o data.
    Paragrap: Ca niciodata.
    Paragrap: Ca daca nu ar fi.
    Paragrap: Nu s-ar mai povestii.
    Paragrap: sfarsit.
    Paragrap: 2A fost o data.
    Paragrap: 2Ca niciodata.
    Paragrap: 2Ca daca nu ar fi.
    Paragrap: 2Nu s-ar mai povestii.
    Paragrap: 2sfarsit.
    Paragrap: De mult a fost o data.
    Paragrap: De ca niciodata.
    Paragrap: De daca nu ar fi.
    Paragrap: De ca niciodata.
    Paragrap: De daca nu ar fi.
    Paragrap: De nu s-ar mai povestii.
    Paragrap: De in sfarsit.
    Paragrap: In mult a fost o data.
    Paragrap: In daca nu ar fi.
    Paragrap: In nu s-ar mai povestii.
    Paragrap: In in sfarsit.

    and the output for my problem shoud be something like that

    Root element of the document: book
    BookDetails
    bookName: Pheonix Order
    authorName: J. K. Rolings
    ISBN: 2012314123
    Total capitole: 3
    =====================
    Nume capitol: Capitol 1 Inceput
    10
    Paragrap: A fost o data.
    Paragrap: Ca niciodata.
    Paragrap: Ca daca nu ar fi.
    Paragrap: Nu s-ar mai povestii.
    Paragrap: sfarsit.
    Paragrap: 2A fost o data.
    Paragrap: 2Ca niciodata.
    Paragrap: 2Ca daca nu ar fi.
    Paragrap: 2Nu s-ar mai povestii.
    Paragrap: 2sfarsit.
    =====================
    Nume capitol: Capitol 2 Continuare
    7
    Paragrap: De mult a fost o data.
    Paragrap: De ca niciodata.
    Paragrap: De daca nu ar fi.
    Paragrap: De ca niciodata.
    Paragrap: De daca nu ar fi.
    Paragrap: De nu s-ar mai povestii.
    Paragrap: De in sfarsit.
    =====================
    Nume capitol: Capitol 3 Sfarsit
    4
    Paragrap: In mult a fost o data.
    Paragrap: In daca nu ar fi.
    Paragrap: In nu s-ar mai povestii.
    Paragrap: In in sfarsit.

    After one hour and some trys, i found a solusion, isn't the best but it work for me, so if anyone want to try something like that you can try my code.

     
    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 XMLParser {
     
        public void getAllUserNames(String fileName) {
            try {
                DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                DocumentBuilder db = dbf.newDocumentBuilder();
                File file = new File(fileName);
                if (file.exists()) {
                    Document doc = db.parse(file);
                    Element docEle = doc.getDocumentElement();
     
                    // Print root element of the document
                    System.out.println("Root element of the document: "
                            + docEle.getNodeName());
     
     
                    //Printare detalii carte.
                    NodeList studentList1 = docEle.getElementsByTagName("bookDetails");
     
                    Node node1 = studentList1.item(0);
     
                    if (node1.getNodeType() == Node.ELEMENT_NODE) {
     
                        System.out.println("BookDetails");
     
                        Element e = (Element) node1;
                        NodeList nodeList1 = e.getElementsByTagName("bookName");
                        System.out.println("bookName: "
                                + nodeList1.item(0).getChildNodes().item(0)
                                .getNodeValue());
                        nodeList1 = e.getElementsByTagName("authorName");
                        System.out.println("authorName: "
                                + nodeList1.item(0).getChildNodes().item(0)
                                .getNodeValue());
                        nodeList1 = e.getElementsByTagName("ISBN");
                        System.out.println("ISBN: "
                                + nodeList1.item(0).getChildNodes().item(0)
                                .getNodeValue());
     
                    }
                    //termnare detalii carte.
                    //{Printare capitole
     
                    NodeList studentList = docEle.getElementsByTagName("chapter");
     
                    // total capitole
                    System.out
                            .println("Total capitole: " + studentList.getLength());
     
                    if (studentList != null && studentList.getLength() > 0) {
                        for (int i = 0; i < studentList.getLength(); i++) {
     
                            Node node = studentList.item(i);
     
                            if (node.getNodeType() == Node.ELEMENT_NODE) {
     
                                System.out
                                        .println("=====================");
     
                                Element e = (Element) node;
                                NodeList nodeList = e.getElementsByTagName("chapterName");
                                System.out.println("Nume capitol: "
                                        + nodeList.item(0).getChildNodes().item(0)
                                        .getNodeValue());
     
     
                                //Pentru fiecare sentence dintr-un capitol.
                                NodeList studentList2 = docEle.getElementsByTagName("chapter");
                                NodeList studentList5 = docEle.getElementsByTagName("Paragrap" + (i + 1));
     
                                System.out.println(studentList5.getLength());
     
                                if (studentList2 != null && studentList2.getLength() > 0) {
                                    //paragrafe 
     
     
                                    for (int k = 0; k < studentList5.getLength(); k++) {
     
                                        Node node2 = studentList2.item(k);
     
                                        if (node.getNodeType() == Node.ELEMENT_NODE) {
                                            nodeList = e.getElementsByTagName("Paragrap" + (i + 1));
                                            System.out.println("Paragrap: "
                                                    + nodeList.item(k).getChildNodes().item(0)
                                                    .getNodeValue());
                                        }
                                    }
     
                                } else {
                                    System.exit(1);
                                }
                            }
                        }
                    } else {
                        System.exit(1);
                    }
                }
            } catch (Exception e) {
                System.out.println(e);
            }
        }
     
        public static void main(String[] args) {
     
            XMLParser parser = new XMLParser();
            parser.getAllUserNames("d:\\book1.xml");
        }
    }

    I don't really like becouse i have "Paragrap" + i , but is only the one witch worked as i want.

    Again sorry for crappy variables name, and thanks again, getTextContent() is muck more easy to use thanks for it.
    VISTA = Virus Inside Switch to Apple
    UNIX - Where there is a shell, there's a way.

  4. #4
    Super Moderator curmudgeon's Avatar
    Join Date
    Aug 2012
    Posts
    1,130
    My Mood
    Cynical
    Thanks
    64
    Thanked 140 Times in 135 Posts

    Default Re: XML Parsel problems

    Quote Originally Posted by adrian.tudor View Post
    Sorry for crapy variables name, didn't have time to rename it and make it more visible and precised.
    Thanks for your time, but isn't what i need.

    Your code just print all paragraphs, here is the output.
    Root element of the document: book
    BookDetails
    bookName: Pheonix Order
    authorName: J. K. Rolings
    ISBN: 2012314123
    Total capitole: 3
    Paragrap: A fost o data.
    Paragrap: Ca niciodata.
    Paragrap: Ca daca nu ar fi.
    Paragrap: Nu s-ar mai povestii.
    Paragrap: sfarsit.
    Paragrap: 2A fost o data.
    Paragrap: 2Ca niciodata.
    Paragrap: 2Ca daca nu ar fi.
    Paragrap: 2Nu s-ar mai povestii.
    Paragrap: 2sfarsit.
    Paragrap: De mult a fost o data.
    Paragrap: De ca niciodata.
    Paragrap: De daca nu ar fi.
    Paragrap: De ca niciodata.
    Paragrap: De daca nu ar fi.
    Paragrap: De nu s-ar mai povestii.
    Paragrap: De in sfarsit.
    Paragrap: In mult a fost o data.
    Paragrap: In daca nu ar fi.
    Paragrap: In nu s-ar mai povestii.
    Paragrap: In in sfarsit.
    That's because I left some code that you already have!!! Surely you could use the ideas from my post with your current code and print the chapter headings???

    Our suggestions and code are not for you to simply copy and paste for a full code solution, but to show you the ideas needed for *you* to solve your problem.

  5. #5
    Junior Member adrian.tudor's Avatar
    Join Date
    Dec 2012
    Location
    Bucharest, Romania
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: XML Parsel problems

     
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.Map;
    import java.util.Set;
    import javax.xml.parsers.*;
    import javax.xml.transform.*;
    import javax.xml.transform.dom.*;
    import javax.xml.transform.stream.*;
    import org.w3c.dom.*;
     
    public class CreateXML {
     
        DocumentBuilderFactory documentBuilderFactory;
        DocumentBuilder documentBuilder;
        Document document;
     
     
        public void createXML(Map order_details, ArrayList item_details, String fileName) {
     
            Set set;
            Iterator iterator;
     
            try {
    //              Creating an empty XML Document
     
                documentBuilderFactory = DocumentBuilderFactory.newInstance();
                documentBuilder = documentBuilderFactory.newDocumentBuilder();
                document = documentBuilder.newDocument();
     
    //               Creating XML tree
    //               create the root element and add it to the document
     
                Element orderElement = document.createElement("book");
                document.appendChild(orderElement);
     
                Element orderDetailElement = document.createElement("bookDetails");
                orderElement.appendChild(orderDetailElement);
     
                set = order_details.keySet();
                iterator = set.iterator();
     
    //                create child element acording to the key set,add an attribute, and add to root (orderDetails)
     
                while (iterator.hasNext()) {
     
                    String key = (String) iterator.next();
                    Element detailElement = document.createElement(key);
                    detailElement.appendChild(document.createTextNode((String) order_details.get(key)));
                    orderDetailElement.appendChild(detailElement);
     
                }
     
                for (int i = 0; i < item_details.size(); i++) {
     
    //                  create item element and add item details as child
     
                    Element itemElement = document.createElement("chapter");
                    orderElement.appendChild(itemElement);
     
     
     
                    Element itemId;
                    String itemdetails[] = (String[]) item_details.get(i);
     
                    Element itemId1 = document.createElement("chapterName");;
                    itemId1.appendChild(document.createTextNode(itemdetails[0]));
                    itemElement.appendChild(itemId1);
     
                    for (int j = 1; j < itemdetails.length; j++) {
                        itemId = document.createElement("Paragrap" + (i + 1));
                        itemId.appendChild(document.createTextNode(itemdetails[j]));
     
                        itemElement.appendChild(itemId);
                    }
     
                }
     
    //              create XML file
     
     
                File xmlFile = new File(fileName);
                xmlFile.createNewFile();
                FileOutputStream isod = new FileOutputStream(xmlFile);
                TransformerFactory transformerFactory = TransformerFactory.newInstance();
                Transformer transformer = transformerFactory.newTransformer();
     
                DOMSource source = new DOMSource(document);
                StreamResult result = new StreamResult(isod);
                transformer.transform(source, result);
     
                isod.flush();
                isod.close();
     
            } catch (IOException ex) {
                ex.printStackTrace();
            } catch (TransformerException ex) {
                ex.printStackTrace();
            } catch (ParserConfigurationException ex) {
                ex.printStackTrace();
            }
     
        }
     
        public static void main(String[] args) {
     
     
            CreateXML cXML = new CreateXML();
            Map order_details = new HashMap();
            ArrayList item_details = new ArrayList();
            String itemDetails[] = new String[4];
            String itemDetails2[] = new String[4];
            String itemDetails3[] = new String[4];
     
    //     add order details       
            order_details.put("ISBN", "2012314123");
            order_details.put("bookName", "Pheonix Order");
            order_details.put("authorName", "J. K. Rolings");
     
    //     add item details
            itemDetails2[0] = "Chapter 1 inceput";
            itemDetails2[1] = "ARR01";
            itemDetails2[2] = "DCL White Arak";
            itemDetails2[3] = "1";
            item_details.add(itemDetails2);
     
            itemDetails2[0] = "Chapter 2 continuare";
            itemDetails2[1] = "ARR02";
            itemDetails2[2] = "Lemon Gin";
            itemDetails2[3] = "2";
            item_details.add(itemDetails2);
     
            itemDetails2[0] = "Chapter 3 Sfarsit";
            itemDetails2[1] = "ARR03 wda ada  hashd ahdau adhauhda uhsd ad audha. adasdauh . adasa";
            itemDetails2[2] = "Ritz";
            itemDetails2[3] = "10";
     
            item_details.add(itemDetails2);
     
            cXML.createXML(order_details, item_details, "d:\\book2.xml");
     
        }
    }

    Why when i add to arraylist, the items what i add in it, it dosn't save in it.

    i want to use this part
            itemDetails2[0] = "Chapter 1 inceput";
            itemDetails2[1] = "ARR01";
            itemDetails2[2] = "DCL White Arak";
            itemDetails2[3] = "1";
            item_details.add(itemDetails2);
    in a for but i can't becouse it save only the last one.
    VISTA = Virus Inside Switch to Apple
    UNIX - Where there is a shell, there's a way.

Similar Threads

  1. convert excel to xml and read the input from xml file
    By rahulruns in forum Object Oriented Programming
    Replies: 5
    Last Post: April 3rd, 2012, 11:13 AM
  2. Reading XML File using DOMParser and have problem with accessing xml
    By optiMystic23 in forum What's Wrong With My Code?
    Replies: 2
    Last Post: January 21st, 2012, 02:22 PM
  3. i need help with xml
    By programmer1 in forum What's Wrong With My Code?
    Replies: 3
    Last Post: July 25th, 2011, 07:00 PM
  4. [SOLVED] Write an xml dom to a xml file
    By Kakashi in forum File I/O & Other I/O Streams
    Replies: 2
    Last Post: March 2nd, 2011, 03:30 PM
  5. java xml-rpc response parsing to xml
    By kievari in forum File I/O & Other I/O Streams
    Replies: 0
    Last Post: November 19th, 2009, 02:36 PM