Runtime error to get the attribute value of an element

M

Matt

mydoc.xml
=========
<?xml version = "1.0"?>
<persons>
<person name="Joe" age="22" />
</persons>


In mydox.xml, I want to get the attribute values of element person. Of
course,
in the actual XML file, it is more complicated.

However, I get the following run-time error,
Exception in thread "main" java.lang.NullPointerException
at ParserTest.main(ParserTest2.java:18) on line
element.hasAttribute("name")


import java.io.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
import org.w3c.dom.*;
import javax.xml.parsers.*;
import org.xml.sax.*;

public class ParserTest2
{
public static void main(String[] args) throws
ParserConfigurationException, SAXException
{
String xmlFile = "mydoc.xml";
doc = getDocumentFromFile(xmlFile);
Element element = doc.getElementById("person");
//Exception in thread "main" java.lang.NullPointerException
if (element.hasAttribute("name"))
{ System.out.println("attribute = " + element.getAttribute("name"));
}
}

public static Document getDocumentFromFile(String xmlFile)
{
try
{
DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new File(xmlFile));
return doc;
}
catch(IOException e)
{ e.printStackTrace();
return null;
}
catch(SAXException e)
{ e.printStackTrace();
return null;
}
catch(ParserConfigurationException e)
{ e.printStackTrace();
return null;
}
}

private static Document doc;
}



any ideas? Thanks!!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,983
Messages
2,570,187
Members
46,747
Latest member
jojoBizaroo

Latest Threads

Top