Jsoup select and iterate all elements

Karthik  picture Karthik · Aug 12, 2011 · Viewed 45.3k times · Source

I will connect to a url through jsoup and get all the contents of it but the thing is if I select like,

doc.select("body")

its returning a single element but I want to get all the elements in the page and iterate them one by one for example,

<html>
<head><title>Test</title></head>
<body>
<p>Hello All</p>
<a href="test.html">Second Page</a>
<div>Test</div>
</body>
</html>

If I select using body I am getting the result in a single line like,

Test Hello All Second Page Test

Instead I want to select all elements and iterate one by one and produce the results like,

Test
Hello All
Second Page
Test

Will that be possible using jsoup?

Thanks,
Karthik

Answer

BalusC picture BalusC · Aug 12, 2011

You can select all elements of the document using * selector and then get text of each individually using Element#ownText().

Elements elements = document.body().select("*");

for (Element element : elements) {
    System.out.println(element.ownText());
}