Search code examples
xmlkotlinparsingjsoup

Parsing xml data with Jsoup in android studio


I have the following code that doesn't seem to be working:

private fun xmlParse_Jsoup() {
    thread {
        val doc = Jsoup.parse("http://xmlweather.vedur.is/?op_w=xml&type=forec&lang=is&view=xml&ids=1;422")

        val listItems: Elements = doc.select("ul.list > li")
        for (item in listItems) System.out.println(item.text())

        val strings = doc.getElementsByTag("forecast")
    }
}

For now I'm just trying to read the file, but in the end the output is going to be all the tags under , the ftime, F, D, T and W tags.


Solution

  • First, select all forecast elements:

    val listItems: Elements = doc.select("forecast")
    

    Next, loop through your list and print the desired children:

    for (item in listItems) {
        System.out.println(item.select("ftime"));
        System.out.println(item.select("f"));
        System.out.println(item.select("d"));
        System.out.println(item.select("t"));
        System.out.println(item.select("w"));
    }
    

    If you only want to print the text contained inside the child nodes, replace the above statements:

    System.out.println(item.select(/* ... */));
    

    with:

    System.out.println(item.select(/* ... */).text());