Diana M. Franco Duran
Diana M. Franco Duran

Reputation: 11

Reading an XML file in Java

I am reading specific information from an XML File. I am having issues trying to read some elements like the DataDate. I am getting a NullPointerException. I think it happens because in the XML file there are two nodes with the word "Project" and the first one does not have a DataDate.

I do not know how to fix this error.

This is a part of the XML File that I am reading: xml

package testReadXML;

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

public class TestReadXML {

    public static void main(String[] args) {

        try {   

            File xmlFile = new File("C:/Users/diani/Downloads/XML Files/CS01.xml");

            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(xmlFile);

            doc.getDocumentElement().normalize();
            System.out.println("Root element:" + doc.getDocumentElement().getNodeName());

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

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

                    Node nNode = nList.item(i);
                    System.out.println("\n" + nNode.getNodeName());

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

                            Element eElement = (Element) nNode;

                            System.out.println("Object Id : " + eElement.getAttribute("ObjectId"));
                            System.out.println("Id : " + eElement.getElementsByTagName("Id").item(0).getTextContent());
                            System.out.println("Name : " + eElement.getElementsByTagName("Name").item(0).getTextContent());         
                            System.out.println("Data Date : " + eElement.getElementsByTagName("DataDate").item(0).getTextContent());  
                        }
                }

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

Upvotes: 1

Views: 248

Answers (1)

Ashish Shetkar
Ashish Shetkar

Reputation: 1467

Just add this If condition when you are fetching the elements

 if(eElement.getElementsByTagName("DataDate").getLength() > 0) {

                        System.out.println("Object Id : " + eElement.getAttribute("ObjectId"));
                        System.out.println("Id : " + eElement.getElementsByTagName("Id").item(0).getTextContent());
                        System.out.println("Name : " + eElement.getElementsByTagName("Name").item(0).getTextContent());
                        System.out.println("Data Date : " + eElement.getElementsByTagName("DataDate").item(0).getTextContent());
                    }

Upvotes: 1

Related Questions