簡體   English   中英

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

[英]Why getChild() method of JDOM returns null?

我正在做一個關於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"));
}

請參考這些..我的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]/>]

我在你的代碼中發現了一些問題: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的子root.getChild("body") ,其名稱為“body”,沒有名稱空間。 您應該檢查您要查找的元素的名稱空間; 如果它有一個合格的命名空間,你必須以這種方式傳遞它:

root.getChild("body", Namespace.getNamespace("your_namespace_uri"));

要知道哪個命名空間有一個簡單的元素,你應該使用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"));

是什么讓你覺得你需要org.ccil.cowan.tagsoup.Parser? 它為您提供了內置於JDK中的解析器不具備哪些功能?

我會嘗試使用SAXBuilder的另一個構造函數。 使用JDK中內置的解析器,看看是否有幫助。

首先使用XMLOutputter打印整個樹。

public static void getBody() 
{
    SAXBuilder builder = new SAXBuilder(true);
    Document document = builder.build("http://www......com");
    XMLOutputter outputter = new XMLOutputter();
    outputter.output(document, System.out);  // do something w/ exception
}
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", Namespace.getNamespace("my_name_space")));
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM