Following example will showcase parsing an HTML String into a Document object.
Document document = Jsoup.parse(html);
Where
document − document object represents the HTML DOM.
Jsoup − main class to parse the given HTML String.
html − HTML String.
The parse(String html) method parses the input HTML into a new Document. This document object can be used to traverse and get details of the html dom.
Create the following java program using any editor of your choice in say C:/> jsoup.
JsoupTester.java
import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; public class JsoupTester { public static void main(String[] args) { String html = "<html><head><title>Sample Title</title></head>" + "<body><p>Sample Content</p></body></html>"; Document document = Jsoup.parse(html); System.out.println(document.title()); Elements paragraphs = document.getElementsByTag("p"); for (Element paragraph : paragraphs) { System.out.println(paragraph.text()); } } }
Compile the class using javac compiler as follows:
C:\jsoup>javac JsoupTester.java
Now run the JsoupTester to see the result.
C:\jsoup>java JsoupTester
See the result.
Sample Title Sample Content