我正在做一个关于 html 文档操作的项目。我想将现有 html 文档中的正文内容修改为新的 html。现在我正在使用 JDOM。我想在我的编码中使用 body 元素。为此,我在我的编码中使用了 getChild("body")。但是它向我的程序返回 null。但是我的 html 文档有一个 body 元素。有人可以帮助我知道这个问题吗我是学生?
希望得到指点..
编码:
import org.jdom.Document;
import org.jdom.Element;
public static void getBody() {
SAXBuilder builder = new SAXBuilder("org.ccil.cowan.tagsoup.Parser", true);
org.jdom.Document jdomDocument=builder.build("http://www......com");
Element root = jdomDocument.getRootElement();
//It returns null
System.out.println(root.getChild("body"));
}
也请引用这些..我的 html 的根和 child 打印在控制台中...
root.getName():html
SIZE:2
[Element: <head [Namespace: http://www.w3.org/1999/xhtml]/>]
[Element: <body [Namespace: http://www.w3.org/1999/xhtml]/>]
最佳答案
我在您的代码中发现了一些问题: 1) 如果你想通过网络构建一个远程 xml,你应该使用另一个接收 URL 作为输入的构建方法。实际上,您正在将名称为“www......com”的文件解析为 xml。
Document jdomDocument = builder.build( new URL("http://www........com"));
2) 如果你想把一个html页面解析成xml,你必须检查它是一个格式正确的xhtml文档,否则你不能把它解析成xml
3) 正如我在另一个答案中已经说过的那样,root.getChild("body")
返回 root 的 child ,其名称为“body”,没有 namespace 。您应该检查您要查找的元素的 namespace ;如果它有一个合格的命名空间,你必须以这种方式传递它:
root.getChild("body", Namespace.getNamespace("your_namespace_uri"));
要以一种简单的方式知道哪个 namespace 有您的元素,您应该使用 getChildren 方法打印出所 Root过的子元素:
for (Object element : doc.getRootElement().getChildren()) {
System.out.println(element.toString());
}
如果您尝试解析 xhtml,可能您有命名空间 uri http://www.w3.org/1999/xhtml
。所以你应该这样做:
root.getChild("body", Namespace.getNamespace("http://www.w3.org/1999/xhtml"));
关于java - 为什么 JDOM 的 getChild() 方法返回 null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5259321/