2016-10-28 90 views
0

我試圖將下面列表中的「」(info.net,test.com等)之間的文本與jsoup相加,並將它們添加到arraylist中。JSoup沒有解析元素

<?xml version="1.0" encoding="UTF-8"?> 
<supported-filehosts> 
<host url="info.net"/> 
<host url="test.com"/> 
<host url="app.to"/> 
</supported-filehosts> 

似乎很容易,但我不能老是用右鍵下面的代碼獲得它:

Document doc = Jsoup.parse(HOSTS); 
Elements links = doc.select("host[url]"); 

for (Element link : links) { 
    hostUrls.add(link.text()); 
} 

有人能看看。

回答

0

你需要從每個標籤attribute

hostUrls.add(link.attr("url")); 

示例代碼:

public class Main { 

    public static void main(String[] args) throws IOException { 


     final String HOSTS = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"+ 
      "<supported-filehosts>"+ 
      "<host url=\"info.net\"/>"+ 
      "<host url=\"test.com\"/>"+ 
      "<host url=\"app.to\"/>"+ 
      "</supported-filehosts>"; 
     List<String> hostUrls = new ArrayList<String>(); 

     Document doc = Jsoup.parse(HOSTS); 
     Elements links = doc.select("host[url]"); 
     for (Element link : links) { 
      hostUrls.add(link.attr("url")); 
     } 
     System.out.println(hostUrls.toString()); 
    } 
} 

輸出:

[info.net,test.com,應用。到]

+0

嗨TDG,thx回覆,但不幸hostUrls仍然是空的 – Simon

+0

我已經添加**完整的代碼**,適合我。 – TDG

+0

奇怪,我現在給鏈接直接解析(Document doc = Jsoup.parse(「http://test.org/filehosts.xml」);還沒有什麼 – Simon