使用jdom从xml获取body标签的子项时出错

时间:2011-03-07 12:41:11

标签: java xml jdom

我需要遍历JDOM树并从body部分提取所有数据,以便在另一个xml文档创建中使用它。我对编程很新。我附上了控制台中显示的概念和错误。我想澄清这个概念是对还是错。任何人都能帮助我了解这个并给出指示吗?

非常感谢任何指示......

//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;
}

显示错误:

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 个答案:

答案 0 :(得分:0)

因此根据评论您的问题是root.getChild("body")。此方法返回null(根元素中没有名为body的子代)。您应该从方法中检查null和return null

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

修改 根据评论,你可以打印(或任何你想做的)所有元素。

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>adfg@gmail.com</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;
    }
}