为什么JDOM的getChild()方法返回null?

Aru*_*run 3 html java xml jdom

我正在做一个关于html文档操作的项目.我希望现有的html文档中的正文内容将其修改为新的html.现在我正在使用JDOM.我想在我的编码中使用body元素.因为我在编码中使用了getChild("body").但它将null返回给我的program.But我的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"));
}
Run Code Online (Sandbox Code Playgroud)

请参考这些..我的html的root和childs在控制台中打印...

root.getName():html

SIZE:2

[Element: <head [Namespace: http://www.w3.org/1999/xhtml]/>]

[Element: <body [Namespace: http://www.w3.org/1999/xhtml]/>]
Run Code Online (Sandbox Code Playgroud)

jav*_*nna 8

我在你的代码中发现了一些问题:1)如果你想通过网络构建一个远程xml,你应该使用另一个接收URL作为输入的构建方法.实际上,您正在使用名称"www ...... com"将文件解析为xml.

Document jdomDocument = builder.build( new URL("http://www........com"));
Run Code Online (Sandbox Code Playgroud)

2)如果你想将一个html页面解析为xml,你必须检查它是一个格式正确的xhtml文档,否则你不能将它解析为xml

3)正如我在另一个回答中已经说过的那样,root.getChild("body")返回root的子名称为"body",没有名称空间.您应该检查您要查找的元素的名称空间; 如果它有一个合格的命名空间,你必须以这种方式传递它:

root.getChild("body", Namespace.getNamespace("your_namespace_uri"));
Run Code Online (Sandbox Code Playgroud)

要知道哪个命名空间有一个简单的元素,你应该使用getChildren方法打印出所有root的子元素:

for (Object element : doc.getRootElement().getChildren()) {
    System.out.println(element.toString());
}
Run Code Online (Sandbox Code Playgroud)

如果您正在尝试解析xhtml,可能您有名称空间uri http://www.w3.org/1999/xhtml.所以你应该这样做:

root.getChild("body", Namespace.getNamespace("http://www.w3.org/1999/xhtml"));
Run Code Online (Sandbox Code Playgroud)