Simon Simon - 1 month ago 11
Android Question

JSoup does not parse elements

I`m trying to get the text between the "" (info.net, test.com etc) of below list with jsoup and add them to an arraylist.

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


Seems easy but I can`t get it right with below code:

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

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


Could somebody have a look.

TDG TDG
Answer

You need to get the attribute from each tag:

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

Example code:

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());
    }   
}  

Output:

[info.net, test.com, app.to]

Comments