NullPointer Exception error while reading a XML

Hi –

I am getting following error while trying to read and display a content from an XML file.

Exception in thread “main” java.lang.NullPointerException
at firstPackage.ReadXml.main(


public class ReadXml {
public static void main(String[] args) throws ParserConfigurationException,

SAXException, IOException {
File xmlFile = new File(System.getProperty("user.dir") + "//Meals.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();

DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();

Document doc = dBuilder.parse(xmlFile);
NodeList nlXml = doc.getChildNodes();

Node nXml = nlXml.item(0);

Element element = (Element) nXml;
System.out.println("Meal: "

+ element.getElementsByTagName("Elements").item(0)


Could you please help with this error? Thanks so much!


Default Asked on November 10, 2014 in Selenium WebDriver.
Add Comment
  • 3 Answer(s)

    Hi Aruna,I think this is the mistake File xmlFile = new File(System.getProperty(“user.dir”) + “//Meals.xml”);  change this line toFile xmlFile = new File(System.getProperty(“user.dir”) + “\\Meals.xml”);

    Train Answered on November 10, 2014.

    Hi Mallik –

    Actually I am using a UBUNTU system, so I had to use the forward slash.

    on November 11, 2014.
    Add Comment

    Hi Aruna

    If i was you then probably i would have used File.seprator instead of hardcoded slashes
    new File(System.getProperty("user.dir")+File.seprator+ "Meals.xml");

    Using this you can run your code on any platform


    Supporter Answered on November 10, 2014.

    Kapilag – I think it can read the XML file, thats not at all an issue. The problem is with the Node, dunno why that is passing the null value.

    on November 11, 2014.

    Aruna can you paste xml as well ?

    on November 11, 2014.
    Add Comment

    As you are using DOM parser. Put the null check after NodeList same as below.

    private String getTextValue(Element ele, String tagName) { String textVal = null; NodeList nl = ele.getElementsByTagName(tagName); if(nl != null && nl.getLength() > 0) { Element el = (Element)nl.item(0); textVal = el.getFirstChild().getNodeValue(); } return textVal; }
    Train Answered on November 17, 2014.
    Add Comment
  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.