|
| 1 | +package com.baeldung.jsoup; |
| 2 | + |
| 3 | +import org.jsoup.Jsoup; |
| 4 | +import org.jsoup.nodes.Document; |
| 5 | +import org.jsoup.safety.Whitelist; |
| 6 | +import org.junit.Test; |
| 7 | +import static org.junit.Assert.assertEquals; |
| 8 | + |
| 9 | +public class PreservingLineBreaksUnitTest { |
| 10 | + |
| 11 | + @Test |
| 12 | + public void whenBackSlashNNewLineCharacter_thenPreserveLineBreak() { |
| 13 | + String strHTML = "<html><body>Hello\nworld</body></html>"; |
| 14 | + Document.OutputSettings outputSettings = new Document.OutputSettings(); |
| 15 | + outputSettings.prettyPrint(false); |
| 16 | + String strWithNewLines = Jsoup.clean(strHTML, "", Whitelist.none(), outputSettings); |
| 17 | + assertEquals("Hello\nworld", strWithNewLines); |
| 18 | + } |
| 19 | + |
| 20 | + @Test |
| 21 | + public void whenHTMLNewLineCharacters_thenPreserveLineBreak() { |
| 22 | + String strHTML = "<html><body>" + |
| 23 | + "Hello" + |
| 24 | + "<br>" + |
| 25 | + "World" + |
| 26 | + "<p>Paragraph</p>" + |
| 27 | + "</body></html>"; |
| 28 | + Document jsoupDoc = Jsoup.parse(strHTML); |
| 29 | + Document.OutputSettings outputSettings = new Document.OutputSettings(); |
| 30 | + outputSettings.prettyPrint(false); |
| 31 | + jsoupDoc.outputSettings(outputSettings); |
| 32 | + jsoupDoc.select("br").before("\\n"); |
| 33 | + jsoupDoc.select("p").before("\\n"); |
| 34 | + String str = jsoupDoc.html().replaceAll("\\\\n", "\n"); |
| 35 | + String strWithNewLines = |
| 36 | + Jsoup.clean(str, "", Whitelist.none(), outputSettings); |
| 37 | + assertEquals("Hello\nWorld\nParagraph", strWithNewLines); |
| 38 | + } |
| 39 | +} |
0 commit comments