2013-03-01 74 views
0

我最近開始使用Jsoup。我需要列出HTML源代碼中的一些元素。例如:Jsoup - 逐個閱讀

<table class="list"> 
    <tr> 
     <td class="year" colspan="5">2012</td> 
    </tr> 
    <tr> 
     <td class="code">COMP0348</td> 
     <td class="name">Software Engineering</td> 
    </tr> 
    <tr> 
     <td class="code">COMP0734</td> 
     <td class="name">System Information</td> 
    </tr> 
    <td class="year" colspan="5">2013</td> 
    </tr> 
    <tr> 
     <td class="code">COMP999</td> 
     <td class="name">Windows</td> 
    </tr> 
</table> 

這就是我想要的:

2012 
Comp0348 Software Engineering 
COMP0734 System Information 
2013 
COMP999 Windows 

但在我的代碼,它沒有一一列出,這是清單包含首先「年」一個字符串,後在另一行中包含所有「代碼」,在另一行中包含所有「名稱」。 Like:

2012 
Comp0348 COMP0734 COMP999 
Software Engineering System Information Windows 

我該怎麼做?

+0

顯示您的jsoup相關的代碼 – SRy 2013-03-01 18:10:24

回答

0

我想你只按標準選擇標籤,而不是結構。

但在這裏看到:

Document doc = ... 

Element table = doc.select("table.list").first(); // select the table 


for(Element element : table.select("tr")) // select all 'tr' of the table 
{ 
    final Elements td = element.select("td.year"); // select the 'td' with 'year' class 

    if(!td.isEmpty()) // if it's the one with the 'year' class 
    { 
     final String year = td.first().text(); // get year 

     System.out.println(year); 
    } 
    else // if it's another 'tr' tag containing the 'code' and 'name' element 
    { 
     final String code = element.select("td.code").first().text(); // get code 
     final String name = element.select("td.name").first().text(); // get name 

     System.out.println(code + " " + name); 
    } 
} 

輸出(使用HTML):

2012 
COMP0348 Software Engineering 
COMP0734 System Information 
2013 
COMP999 Windows