0

I am trying to read from xml file but I get a null pointer exception. this is the xml file:

<war>
    <missileLaunchers> 
        <launcher  id="L101" isHidden="false">
            <missile  id="M1" destination="Sderot" launchTime="2" flyTime="12" damage="1500"/>
            <missile id="M2" destination="Beer-Sheva" launchTime="5" flyTime="7" damage="2000"/>
        </launcher>
        <launcher id="L102" isHidden="true">
            <missile id="M3" destination="Ofakim" launchTime="4" flyTime="3" damage="5000"/>
            <missile id="M4" destination="Beer-Sheva" launchTime="9" flyTime="7" damage="1000"/>
        </launcher>
    </missileLaunchers>
    <missileDestructors >
        <destructor  id="D201">
            <destructdMissile  id="M1" destructAfterLaunch="4"/>
            <destructdMissile id="M3" destructAfterLaunch="7" />
            <destructdMissile id="M4" destructAfterLaunch="2"/>
        </destructor>
        <destructor id="D202">
            <destructdMissile id="M2" destructAfterLaunch="3"/>
        </destructor>
    </missileDestructors>
    <missileLauncherDestructors >
        <destructor type="plane" >
            <destructedLanucher  id="L101" destructTime="4"/>
        </destructor>
        <destructor type="ship">
            <destructedLanucher id="L102" destructTime="8" />
            <destructedLanucher id="L102" destructTime="12"/>
        </destructor>
    </missileLauncherDestructors>
</war>

and this is the code:

public class XmlReader
{

File fXmlFile=null; 
DocumentBuilderFactory dbFactory=null;
DocumentBuilder dBuilder=null;
Document doc=null;

public XmlReader(String filePath) throws ClassNotFoundException
{
    if(filePath!=null)
    {
        this.fXmlFile = new File(filePath);     

        dbFactory = DocumentBuilderFactory.newInstance();
        try {
            dBuilder = dbFactory.newDocumentBuilder();
        } catch (ParserConfigurationException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        try {
            doc = dBuilder.parse(fXmlFile);
            doc.getDocumentElement().normalize();
        } catch (SAXException | IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    else System.out.println("Xml file not found");

}
//gets value by tag name
private static String getTagValue(String tag, Element element) {

    if(element.hasChildNodes())
    {
        NodeList nodeList = element.getElementsByTagName(tag).item(0).getChildNodes();          
        Node node = (Node) nodeList.item(0);
        if(node==null)
            return null;
        return node.getNodeValue();
    }

    else return element.getNodeValue();

}

//launcher
public List<Launcher> readLauncher() throws Exception
{           
    List<Launcher> launcherList = new ArrayList<Launcher>();
    try
    {
        NodeList nList = doc.getElementsByTagName("launcher");

        for(int i=0;i<nList.getLength();i++)
        {launcherList.add(getLauncher(nList.item(i)));}
    }

    catch (Exception e) 
    {
        e.printStackTrace();                
    }
    return launcherList;
}

//builds the object
private static Launcher getLauncher(Node node) 
{
    //XMLReaderDOM domReader = new XMLReaderDOM();
    Launcher launcher = new Launcher();
    if (node.getNodeType() == Node.ELEMENT_NODE)
    {
        Element element = (Element) node;                     
        //   launcher.setIsHidden(Boolean.parseBoolean(getTagValue("isHidden", element)));
        //   launcher.setId(getTagValue("id", element));
        System.out.println("id = "+getTagValue("id", element));
        System.out.println("ishidden = "+getTagValue("isHidden", element));     
    }

    return launcher;
 }
}

And this is the stack trace:

java.lang.NullPointerException
    at XmlReader.getTagValue(XmlReader.java:56)
    at XmlReader.getLauncher(XmlReader.java:96)
    at XmlReader.readLauncher(XmlReader.java:78)
    at Program.main(Program.java:27)

I can not change the format of the xml file. It seems to fail when it tries to get the actual value of the node's fields or so I assume. Though I don;t understand the reason...when I check the size of the node list it turns fine it does give me 2.

6
  • regarding "at XmlReader.getTagValue(XmlReader.java:56)" -- What line is line 56? More importantly, you need to learn the general concepts of how to debug a NPE (NullPointerException). You should inspect the line carefully that throws it (here line 56 of your XmlReader class), find out which variable is null, and then trace back into your code to see why. You will run into these again and again, trust me. Commented Jul 20, 2014 at 19:30
  • inside: String getTagValue(String tag, Element element) line 56 is: if(node==null) Commented Jul 20, 2014 at 19:38
  • This line, if(node==null) can't be the line that throws the exception. A more likely suspect is the line immediately above it. Re-run your program to verify the location of where the NPE is being thrown since that is key. Commented Jul 20, 2014 at 19:39
  • reran and got a new stack. java.lang.NullPointerException at XmlReader.getTagValue(XmlReader.java:54) at XmlReader.getLauncher(XmlReader.java:94) at XmlReader.readLauncher(XmlReader.java:74) at Program.main(Program.java:27) Commented Jul 20, 2014 at 19:40
  • how do I do a new line in this "add coment box" ? to sum up : lines 54,94,74,27. line 54 is :NodeList nodeList = element.getElementsByTagName(tag).item(0).getChildNodes(); Commented Jul 20, 2014 at 19:41

2 Answers 2

1

The problem is below line:

 System.out.println("id = " + getTagValue("id", element));

where getTagValue("id", element) is calling

NodeList nodeList = element.getElementsByTagName(tag).item(0).getChildNodes();

Here element.getElementsByTagName("id") will return null

It should be get from attribute

// gets value by tag name
private static String getTagValue(String tag, Element element) {
    return element.getAttributeNode(tag).getValue();
}
Sign up to request clarification or add additional context in comments.

4 Comments

I changed it to NodeList nodeList = element.getAttributeNode(tag).getChildNodes(); thanks it works
simply return element.getAttributeNode(tag).getValue() from method getTagValue. There is no need to get child nodes. It should be element.getAttributeNode(tag).getValue()
What is failed? explain a bit more. you have posted a new question just now. Is that address this new issue?
not new issue . I apologize, u replied too early,I didn't have enough time to correct. It's fine it was my bad.
1

You are calling getElementsByTagName() in getTagValues, however you are trying to retrieve attributes of the tag. You may need to call getAttribute() instead. For Example:

element.getAttribute(attributeName)

where attributeName is "id" or "isHidden". This will return the value as a String and can be returned directly with no further processing.

2 Comments

could u give me an example? NodeList nodeList = element.getAttribute(tag); doesn;t work
That call will return the value as a String so you can return it directly without assigning it to a nodeList.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.