2013-08-04 95 views
1

我有一點複雜,髒的html代碼。有沒有一個好的HTML解析器可以將HTML代碼用作Java對象?Java的HTML對象

例如我想訪問該代碼:通過DOM

<html> 
    <body> 
    <div id='foo'> 
    <p id='bar'></p> 
    </div> 
    </body> 
</html> 

,如:

[File/Code].getElementById('foo').appendText('bla'); 
[File/Code].getElement(Element.DIV).getElement(ELEMENT.P).getValue(); 
//etc... 

有別人的想法?

或者Java中是否存在DOM(this does not help :()?

問候

+1

看看[JSoup(http://jsoup.org/) –

+0

是,jsoup就是我搜索:) – criztovyl

回答

2

只要給http://jsoup.org/一試。它可以處理非常糟糕的html。

例子:

public static void main(String[] args) 
{ 
    Document document = Jsoup.parse("<html>" + 
      " <body>" + 
      " <div id='foo'>" + 
      "  <p id='bar'>TEST</p>" + 
      " </div>" + 
      " </body>" + 
      "</html>"); 

    System.out.println("Add blah to the Element with ID: foo"); 
    Element foo = document.getElementById("foo"); 
    foo.appendText("blah"); 

    System.out.println(document.html()); 

    System.out.println("Get the content of a div having a p:"); 
    for (Element div : document.getElementsByTag("div")) 
    { 
     for (Element p : div.getElementsByTag("p")) 
     { 
      System.out.println(p.text()); 
     } 

    } 
} 

Maven的

<dependency> 
    <groupId>org.jsoup</groupId> 
    <artifactId>jsoup</artifactId> 
    <version>1.7.2</version> 
</dependency> 
+0

@criztovyl_needs_help你是否需要更多信息來接受這個答案? – d0x

+0

我接受此答案與更多信息,現在使用jsoup :) – criztovyl

+0

_ahem_,*信息。 – criztovyl