2013-04-03 31 views
0

我有一個HTML頁面,我試圖從中挖掘出Logname的值。我可以將所有li文本作爲一個字符串擠在一起,但不是我想要的。我只想在</span>之後的li Logname的第二部分。任何方式輕鬆獲得?用我所擁有的,我可以做一個分裂並得到我想要的,但似乎應該有一個更優雅的方式?Jsoup嵌套列表項內的值

當前代碼

Elements detail = mHtml.select ("div.alpha-first"); 


     for (Element items : detail) 
     { 
      Log.d (TAG, " label text " + items.text()); 

      detail. 

      if (items.text().equals ("ACID")) 
      { 
       Log.d (TAG, " got ACID "); 
      } 

     } 

HTML

<html> 
<title>emp id chart</title> 
<body> 
<div class="alpha-first"> 
     <ul class="account-detail"> 
     <li><span class="label">ID</span>42</li> 
     <li><span class="label">Logname</span>George</li> 
     <li><span class="label">Surname</span>Glass</li> 
     <li><span class="label">ACID</span>15</li> 
     <li><span class="label">Dept</span>101348</li> 
     <li><span class="label">Empclass</span>Echo</li> 
     </ul> 
     <p class="last-swipe">3 Apr 9:53</p><br> </div> 
    <div class="detail-last-loc"> 
     <p style="font-size: 8pt;">Current status</p> 
     <p class="current-location">Bldg #23 South Lot</p> 
     <p> current time 10:43 <br /></p> 
     <div class="detail-extra"> 
     <p><a href="/empswipe/history/151034842">More</a> | <a href="/empswipe/history/151034842/3">3 Day History</a></p> 
     </div> 
</div> 
</body> 
</html> 

回答

2

從我的理解,給你的榜樣,你會想從獲得:<li><span class="label">Logname</span>George</li>,值:George

你真的不需要迭代,你可以直接得到它。我不會去這麼稱呼這個代碼優雅,但仍然,在這裏它是:

//Select the <span> element the text "Logname" 
    Elements select = mHtml.select(".account-detail span.label:contains(Logname)"); 

    //Get the element itself, since the select returns a list 
    Element lognameSpan = select.get(0); 

    //Get the <li> parent of the <span> 
    Element parent = lognameSpan.parent(); 

    //Access the text node of the <li> directly since there is only one 
    String logname = parent.textNodes().get(0).text(); 

希望它有幫助。

+0

謝謝,這正是我想要做的。我的示例代碼有點混亂,因爲我在ACID上分支而不是在Logname上分支。 – wufoo