azriebakri
azriebakri

Reputation: 1151

How to iterate through XML tags using Jsoup?

Currently I have the following XML something like this:

<item>
   <title> this is title 1 </title>
   <description> description 1 </description>
   <pubDate> date 1 </pubDate>
</item>

<item>
   <title> this is title 2 </title>
   <description> description 2 </description>
   <pubDate> date 2 </pubDate>
</item>

I'm using jsoup but the result that I got is:

this is title 1
this is title 2
description 1
description 2
date 1
date 2

The actual result that I want:

this is title 1
description 1
date 1
this is title 2
description 2
date 2

I'm still a beginner in android. I want to achieve this using Jsoup. A simple sample code would be helpful. Thank you.

Upvotes: 2

Views: 1264

Answers (2)

flavio.donze
flavio.donze

Reputation: 8100

Here is a snippet that prints all children of the item elements:

public class Test {

    public static void main(String[] args) {
        String xml = 
                "<item>\r\n" + 
                "   <title> this is title 1 </title>\r\n" + 
                "   <description> description 1 </description>\r\n" + 
                "   <pubDate> date 1 </pubDate>\r\n" + 
                "</item>\r\n" + 
                "\r\n" + 
                "<item>\r\n" + 
                "   <title> this is title 2 </title>\r\n" + 
                "   <description> description 2 </description>\r\n" + 
                "   <pubDate> date 2 </pubDate>\r\n" + 
                "</item>";

        Document doc = Jsoup.parse(xml, "", Parser.xmlParser());
        for (Element item : doc.select("item")) {
            Elements children = item.children();
            for (Element child : children) {
                System.out.println(child.text());
            }
        }
    }
}

This is the output:

this is title 1
description 1
date 1
this is title 2
description 2
date 2

Upvotes: 2

soorapadman
soorapadman

Reputation: 4509

Try this :

public class Test {
    public static void main(String[] args) {
        String html = "<?xml version=\"1.0\" encoding=\"UTF-8\">" +
                "<item>\n" +
                "   <title> this is title 1 </title>\n" +
                "   <description> description 1 </description>\n" +
                "   <pubDate> date 1 </pubDate>\n" +
                "</item>\n" +
                "\n" +
                "<item>\n" +
                "   <title> this is title 2 </title>\n" +
                "   <description> description 2 </description>\n" +
                "   <pubDate> date 2 </pubDate>\n" +
                "</item></xml>";
        Document doc = Jsoup.parse(html, "", Parser.xmlParser());
        for (Element e : doc.select("item")) {
            System.out.println(e.text());
        }

}

Upvotes: 0

Related Questions