RE: 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!


Aruna Default Asked on November 10, 2014 in Selenium WebDriver.
Add Comment
3 Answers

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.