|
| 1 | +package com.baeldung.xmlhtml.delhtmltags; |
| 2 | + |
| 3 | +import net.htmlparser.jericho.Renderer; |
| 4 | +import net.htmlparser.jericho.Segment; |
| 5 | +import net.htmlparser.jericho.Source; |
| 6 | +import org.htmlcleaner.CleanerProperties; |
| 7 | +import org.htmlcleaner.HtmlCleaner; |
| 8 | +import org.jsoup.Jsoup; |
| 9 | +import org.junit.jupiter.api.Test; |
| 10 | + |
| 11 | +import java.io.IOException; |
| 12 | +import java.net.URISyntaxException; |
| 13 | +import java.nio.file.Files; |
| 14 | +import java.nio.file.Paths; |
| 15 | + |
| 16 | +class RemoveHtmlTagsLiveTest { |
| 17 | + |
| 18 | + @Test |
| 19 | + void givenHtml1_whenRemoveTagsByRegex_thenPrintText() throws IOException, URISyntaxException { |
| 20 | + String html = new String(Files.readAllBytes( |
| 21 | + (Paths.get(getClass().getResource("/xmlhtml/delhtmltags/example1.html").toURI())))); |
| 22 | + String result = html.replaceAll("<[^>]*>", "") |
| 23 | + .replaceAll("(?m)^\\s*$", ""); // remove empty and blank lines |
| 24 | + System.out.println(result); |
| 25 | + } |
| 26 | + |
| 27 | + @Test |
| 28 | + void givenHtml2_whenRemoveTagsByRegex_thenPrintText() throws IOException, URISyntaxException { |
| 29 | + String html = new String(Files.readAllBytes( |
| 30 | + (Paths.get(getClass().getResource("/xmlhtml/delhtmltags/example2.html").toURI())))); |
| 31 | + String result = html.replaceAll("<[^>]*>", ""); |
| 32 | + System.out.println(result); |
| 33 | + } |
| 34 | + |
| 35 | + @Test |
| 36 | + void givenHtml2_whenRemoveTagsByJsoup_thenPrintText() throws IOException, URISyntaxException { |
| 37 | + String html = new String(Files.readAllBytes( |
| 38 | + (Paths.get(getClass().getResource("/xmlhtml/delhtmltags/example2.html").toURI())))); |
| 39 | + System.out.println(Jsoup.parse(html).text()); |
| 40 | + } |
| 41 | + |
| 42 | + @Test |
| 43 | + void givenHtml2_whenRemoveTagsByHtmlCleaner_thenPrintText() throws IOException, URISyntaxException { |
| 44 | + String html = new String(Files.readAllBytes( |
| 45 | + (Paths.get(getClass().getResource("/xmlhtml/delhtmltags/example2.html").toURI())))); |
| 46 | + CleanerProperties props = new CleanerProperties(); |
| 47 | + props.setPruneTags("script"); |
| 48 | + String result = new HtmlCleaner(props).clean(html).getText().toString(); |
| 49 | + System.out.println(result); |
| 50 | + } |
| 51 | + |
| 52 | + @Test |
| 53 | + void givenHtml2_whenRemoveTagsByJericho_thenPrintText() throws IOException, URISyntaxException { |
| 54 | + String html = new String(Files.readAllBytes( |
| 55 | + (Paths.get(getClass().getResource("/xmlhtml/delhtmltags/example2.html").toURI())))); |
| 56 | + Source htmlSource = new Source(html); |
| 57 | + Segment segment = new Segment(htmlSource, 0, htmlSource.length()); |
| 58 | + Renderer htmlRender = new Renderer(segment).setIncludeHyperlinkURLs(true); |
| 59 | + System.out.println(htmlRender); |
| 60 | + } |
| 61 | +} |
0 commit comments