Error while getting children of a body tag from xml using jdom

651 Views Asked by At

I need to walk through a JDOM tree and extract all data from body section to use it in another xml document creation. I'm very new to programming. I have attached my concept and error shown in console. I want to clarify whether this concept is right or wrong. Could any body help me to know about this and give a direction?

Would appreciate any pointers..

//root- Existing document's root.
//body- New documents body.
private static Element listChildren(Element root, int depth) {
    System.out.println(root.getName());
    List children = root.getChild("body").getChildren();
    Iterator iterator = children.iterator();
    while (iterator.hasNext()) {
         Element child = (Element) iterator.next();
         System.out.println(child.toString());
         body.addContent(child);
         listChildren(child, depth+1);
         return child;
    }

    return null;
}

Error shown:

Exception in thread "main" java.lang.NullPointerException
    at createXhtml1.listChildren(createXhtml1.java:85)
    at createXhtml1.newXhtml(createXhtml1.java:62)
    at createXhtml1.main(createXhtml1.java:112)
1

There are 1 best solutions below

12
On BEST ANSWER

So based on comments your problem is with root.getChild("body"). This method returns null (there's no child named body in root element). You should check for null and return null from method.

....
Element element = root.getChild("body")    
if (element == null)
    return null;
List children = element.getChildren();
...

EDIT According to comment, you can print (or whatever you want to do) all elements.

public class Test {
    public static void main(String[] args) throws Exception {
        String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><html> <body> <h1 align=\"center\">Profile</h1><hr /> <div class=\"centered\"> <table><tr><td><strong>Name: </strong></td> <td>A</td> </tr> <tr> <td><strong>Age: </strong></td> <td>23</td> <td>programmer</td></tr><tr><td><strong>Email: </strong></td><td>[email protected]</td></tr></table></div><hr /></body></html>";
        SAXBuilder builder = new SAXBuilder();
        Document doc = builder.build(new StringReader(xml));
        listChildren(doc.getRootElement(), 0);
    }

    private static void listChildren(Element root, int depth) {
        System.out.println(root.getName());
        List<Element> children = root.getChildren();
        if (children == null || children.isEmpty())
                return;
        for (Element child : children) {
                 System.out.println(child.toString());
                 listChildren(child, depth+1);
        }

        return;
    }
}