Lets consider this xml file :
<?xml version="1.0" encoding="UTF-8"?>
<root attribute="value">
<element>myElement</element>
</root>
I’m trying to parse the file using JDOM to extract the attribute name and value from the root element.
This is the code I mad for this purpose :
public static org.jdom.Document document;
public static org.jdom.Element root;
SAXBuilder sxb = new SAXBuilder();
try
{
document = sxb.build(new File("file.xml"));
root = document.getRootElement();
List myList = root.getAttributes();
Iterator x = myList.iterator();
while(x.hasNext())
{
Attribute myAttribute = (Attribute)x.next();
System.out.println("name : " + myAttribute.getName() + " & value : " + myAttribute.getValue());
}
}
catch(Exception e){
e.printStackTrace();
}
Everything works fine for this xml file. But when I use this file :
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE rootElement PUBLIC "-//Project" "mydtd.dtd">
<root attribute="value">
<element>myElement</element>
</root>
I get Exception in thread "main" java.lang.NullPointerException
Do you think I should remove the DOCTYPE from the xml file before parsing it and past it after I finish the parsing.
Or there is something else I can do in this situation ?
Thanks
Yes – never, ever do this:
This is not a problem with JDOM or attributes, this is a problem with your general exception handling.
It’s likely that you’re getting a
NullPointerExceptionbecause the XML file didn’t parse properly, so thedocumentfield isnull. But because you caught and ignored the exception, you get no meaningful error message.Move the all of the code you currently have after the catch block, inside the try/catch block, and you’ll get a more useful error report.