简体   繁体   中英

Jsoup select and iterate all elements

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

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

To get all of the elements within the body of the document using jsoup library.

doc.body().children().select("*");

To get just the first level of elements in the documents body elements.

doc.body().children();

You can use XPath or any library which contain XPath

the expression is //text()

Test the expression with your xml here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM