2017-05-25 78 views
0

想這是我使用過jsoup在Java中jsoup:只是一些標籤(H2)

<div id = "report-content"> 
    <h2>Name <div>or a nick name</div></h2> 
    Doe 
    <h2>Occupation</h2> 
    Singer 
    <h2>Lives in</h2> 
    Honkong 
</div> 

解析如何才能獲取數據,如

Name 
Doe 

Occupation 
Singer 

Lives in 
Honkong 

的HTML後分析數據jsoup?

回答

0

看一看下面的代碼片段:

Document document = Jsoup.parse("<div id = \"report-content\">\r\n" + " <h2>Name <div>or a nick name</div></h2>\r\n" 
     + " Doe\r\n" + " <h2>Occupation</h2>\r\n" + " Singer\r\n" + " <h2>Lives in</h2>\r\n" + " Honkong\r\n" 
     + " </div>"); 

Element rootElement = document.getElementById("report-content"); 
for (Node node : rootElement.childNodes()) { 
    if (node instanceof TextNode) { 
     // print text after h2 tag 
     System.out.println(((TextNode) node).text().trim()); 
    } else if (node instanceof Element) { 
     // print text of the h2 tag without inner elements (div) 
     Element element = (Element) node; 
     if ("h2".equals(element.tagName())) { 
      System.out.println(element.ownText()); 
     } 
    } 
}