使用 jdom 从 xml 获取 body 标记的子级时出错
我需要遍历 JDOM 树并从正文部分提取所有数据,以便在另一个 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)
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
因此,根据评论,您的问题出在
root.getChild("body")
上。此方法返回 null(根元素中没有名为 body 的子元素)。您应该检查 null 并从方法中返回 null
。编辑
根据评论,您可以打印(或任何您想做的事情)所有元素。
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 andreturn null
from method.EDIT
According to comment, you can print (or whatever you want to do) all elements.