HTML Parsers
The HtmlParser class is used to parse HTML into POJOs. They can also parse the contents produced by HtmlDocSerializer.
When to use it
Use HtmlParser to read HTML that HtmlSerializer or HtmlDocSerializer produced, such as a page you saved or a table you posted, back into POJOs.
It understands the table, list and anchor structure Juneau writes; it is not a general web-page scraper.
Example
import org.apache.juneau.marshall.html.*;
public class HtmlParserExample {
public static class Person {
public String name;
public int age;
}
public static void main(String[] args) throws Exception {
Person person = new Person();
person.name = "John Smith";
person.age = 45;
// Serialize to HTML, then parse the HTML back into a bean.
String html = HtmlSerializer.DEFAULT.write(person).toString();
Person copy = HtmlParser.DEFAULT.read(html, Person.class);
System.out.println(html);
System.out.println(copy.name + " " + copy.age);
}
}
A parser also accepts the full document that HtmlDocSerializer writes; it reads the data out of the body and ignores the surrounding template.
Options
The following pre-configured parsers are provided for convenience:
| Instance | Accepts |
|---|---|
HtmlParser.DEFAULT | HTML with the default settings. |
For anything else, start from the builder's create() method. The settings readers reach for first:
| Builder method | Effect |
|---|---|
trimStrings() | Trim whitespace from parsed string values. |
validateEnd() | Fail if anything but whitespace follows the parsed value. |
autoCloseStreams() | Close the input stream or reader when parsing finishes. |
beanDictionary(Class...) | Classes the parser may instantiate from type attributes. |
swaps(Class...) | Object swaps that convert parsed values into other types. |
The class hierarchy for the builder of this parser is below. Refer to the builder javadocs for the full set of configurable settings.
See also
- HTML Serializers: the reverse direction.
- HtmlDocSerializer
- HTML Methodology
- Serializers and Parsers