1

I'm trying to read some XML nodes and store them into a Java object. I can read some of the elements of the object while I can't read others and I don't know why. Here is how a part of the XML looks like:

<problems>
  <problem id = "1">
      <quest>22-16:4</quest>
      <result>18</result>
      <chapter_id>1</chapter_id>
      <type>text</type>
  </problem>
  <problem id = "2">
      <quest>16+2*12</quest>
      <result>30</result>
      <chapter_id>1</chapter_id>      
       <type>text</type>  
  </problem>
  <problem id = "3">
      <quest>72:2-18</quest>
      <result>18</result>
      <chapter_id>1</chapter_id>     
       <type>text</type>   
  </problem>
  <problem id = "4">
      <quest>12*4-15:5</quest>
      <result>45</result>
      <chapter_id>1</chapter_id>   
       <type>text</type>     
  </problem>
</problems>

And here is the XMLHandler:

try {
        Configuration configuration = new Configuration().configure();
        SessionFactory sessionFactory = configuration.buildSessionFactory();
        Session session = sessionFactory.openSession();


    File fXmlFile = new File("C:\\Users\\buciu\\workspace\\teachApp\\xml\\problems.xml");
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(fXmlFile);
    doc.getDocumentElement().normalize();

    NodeList nList = doc.getElementsByTagName("problem");

    for (int temp = 0; temp < nList.getLength(); temp++) {

        Transaction transaction = session.beginTransaction();
        Node nNode = nList.item(temp);

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

            Element eElement = (Element) nNode;

            Problem p = new Problem();
            ChapterDAO chdao=new ChapterDAO();

            p.setQuest(eElement.getElementsByTagName("quest").item(0).getTextContent());
            p.setResult(eElement.getElementsByTagName("result").item(0).getTextContent());
            Chapter c = chdao.findTChapter(eElement.getElementsByTagName("chapter_id").item(0).getTextContent());
            p.setType(eElement.getElementsByTagName("type").item(0).getTextContent());
            p.setChapter(c);

            session.save(p);
            transaction.commit();
            }
        }
    } catch (Exception e) {
    e.printStackTrace();
    }

I can read the quest, result and chapter_id elements, but I cannot read the type element. I used my application without it so far, I just added it as a new element and now I want to create another object, updated.

The error it gives me is simple(pointing at the line with setting the type element):

java.lang.NullPointerException
    at testsManagement.XMLHandler.readXMLProblems(XMLHandler.java:57)
    at Main.main(Main.java:30)

So do you see where is the problem? Thanks!

Paul Buciuman
  • 325
  • 3
  • 10
  • 19

2 Answers2

0

First of all, can you give a snippet of the full module? the error says it's on the line 57 but there are not enough lines to see where actually crashes, it can be that you cannot access propperly, or you're reading an EOF from the Xml. Or, at least, marrk the exact line where it crashes.

Help us to help you :)

  • damn, I have never used a snippet so I don't know now how to create now,but until I look for it, the line that gives error is this one: p.setType(eElement.getElementsByTagName("type").item(0).getTextContent()); Also, if I just comment that line, and not read the type element, it gives no error and works properly – Paul Buciuman Sep 05 '17 at 19:19
  • do you know which tag are you reading? Also, i'm not really sure about it but, isn't "type" a reserved word? – Reyeselda95 Sep 05 '17 at 19:28
  • I changed the name of the tag, to be sure it isn't a reserved one and it's still not working. It's weird cuz everything else it's working, the rest of the tags are read properly – Paul Buciuman Sep 05 '17 at 19:36
  • Ok, the next thing is to assure how many times it iterates. Sometimes getElementsByTagName works strange (don't know why, i haven't programmed it) you need to be sure in which iteration of the loop is crashing your program. It may work well X iterations but just crash on a specific one for reading strange characters or something. – Reyeselda95 Sep 05 '17 at 19:44
  • it breaks right at the first iteration of it, for the type tag – Paul Buciuman Sep 05 '17 at 19:51
  • another thing, try to change the line of chapter, because creating a new object sometimes messes the things. Just change the lines,the code may just throw the same message (or fix it) but will be cleaner. – Reyeselda95 Sep 05 '17 at 21:29
0

You can try the bellow one if you want:

import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class ReadXMLFile {

    public static void main(String argv[]) {
        try {
            File fXmlFile = new File("C:/sample.xml");
            DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance()
                    .newDocumentBuilder();
            Document doc = dBuilder.parse(fXmlFile);
            System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
            if (doc.hasChildNodes()) {
                printNote(doc.getChildNodes());
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

    private static void printNote(NodeList nodeList) {
        System.out.println("nodeList.getLength() = "+nodeList.getLength());
        for (int count = 0; count < nodeList.getLength(); count++) {
            Node tempNode = nodeList.item(count);
            // make sure it's element node.
            if (tempNode.getNodeType() == Node.ELEMENT_NODE) {
                // get node name and value
                System.out.println("Node Name =" + tempNode.getNodeName());
              //  System.out.println("Node Value =" + tempNode.getTextContent());
                if (tempNode.hasAttributes()) {
                    // get attributes names and values
                    NamedNodeMap nodeMap = tempNode.getAttributes();
                    for (int i = 0; i < nodeMap.getLength(); i++) {
                        Node node = nodeMap.item(i);
                        System.out.println("\t attr name : " + node.getNodeName());
                        System.out.println("\t attr value : " + node.getNodeValue());
                    }
                }
                else if (tempNode.hasChildNodes()) {
                    // loop again if has child nodes
                    printNote(tempNode.getChildNodes());
                }
            }

        }

    }
}
Sudha Velan
  • 633
  • 8
  • 24