From ed51104e26ff61c9c245ccfbe53998cb41a2c768 Mon Sep 17 00:00:00 2001 From: vatsalgosar Date: Fri, 31 Jul 2020 01:26:27 +0530 Subject: [PATCH] BAEL-3941 (#9499) * BAEL-3941 - Code snippets for preserving line breaks using Jsoup while parsing HTML strings * BAEL-3941 - swapped the order of arguments in assertEquals --- .../jsoup/PreservingLineBreaksUnitTest.java | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 jsoup/src/test/java/com/baeldung/jsoup/PreservingLineBreaksUnitTest.java diff --git a/jsoup/src/test/java/com/baeldung/jsoup/PreservingLineBreaksUnitTest.java b/jsoup/src/test/java/com/baeldung/jsoup/PreservingLineBreaksUnitTest.java new file mode 100644 index 0000000000..0958fa96e2 --- /dev/null +++ b/jsoup/src/test/java/com/baeldung/jsoup/PreservingLineBreaksUnitTest.java @@ -0,0 +1,39 @@ +package com.baeldung.jsoup; + +import org.jsoup.Jsoup; +import org.jsoup.nodes.Document; +import org.jsoup.safety.Whitelist; +import org.junit.Test; +import static org.junit.Assert.assertEquals; + +public class PreservingLineBreaksUnitTest { + + @Test + public void whenBackSlashNNewLineCharacter_thenPreserveLineBreak() { + String strHTML = "Hello\nworld"; + Document.OutputSettings outputSettings = new Document.OutputSettings(); + outputSettings.prettyPrint(false); + String strWithNewLines = Jsoup.clean(strHTML, "", Whitelist.none(), outputSettings); + assertEquals("Hello\nworld", strWithNewLines); + } + + @Test + public void whenHTMLNewLineCharacters_thenPreserveLineBreak() { + String strHTML = "" + + "Hello" + + "
" + + "World" + + "

Paragraph

" + + ""; + Document jsoupDoc = Jsoup.parse(strHTML); + Document.OutputSettings outputSettings = new Document.OutputSettings(); + outputSettings.prettyPrint(false); + jsoupDoc.outputSettings(outputSettings); + jsoupDoc.select("br").before("\\n"); + jsoupDoc.select("p").before("\\n"); + String str = jsoupDoc.html().replaceAll("\\\\n", "\n"); + String strWithNewLines = + Jsoup.clean(str, "", Whitelist.none(), outputSettings); + assertEquals("Hello\nWorld\nParagraph", strWithNewLines); + } +}