开发者

Why I can't get the attributes from the root element using JDOM

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


Or there is something else I can do in this situation ?

Yes - never, ever do this:

catch(Exception e){}

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 NullPointerException because the XML file didn't parse properly, so the document field is null. 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜