简体   繁体   中英

How to get html preview result as a string from html element with jsoup?

I want to get HTML preview result from the jsoup element. Let say I have the jsoup element that has the following html code:

Element's HTML Code:

<div class="code-container">
<div id="highlighter_245626" class="syntaxhighlighter nogutter   night">
<table border="0" cellpadding="0" cellspacing="0">
<tbody>
<tr>
<td class="code">
<div class="container">
<div class="line number1 index0 alt2"><code class="comments">// C++ program for implementation of FCFS </code></div>
<div class="line number2 index1 alt1"><code class="comments">// scheduling </code></div>
<div class="line number3 index2 alt2"><code class="preprocessor">#include&lt;bits/stdc++.h&gt; </code></div>
<div class="line number4 index3 alt1"><code class="keyword bold">using</code> <code class="keyword bold">namespace</code> <code class="plain">std; </code></div>
</div>
</td>
</tr>
</tbody>
</table>
</div></div>

HTML preview result string:

// C++ program for implementation of FCFS
#include<bits/stdc++.h>
using namespace std;

I have tried to get HTML preview string with Element.Text() And I have the following problems:

  • Broken line endings
  • Irregular spacings

Is there a better way to get HTML preview result as a string from HTML element with jsoup?

This will preserve line breaks for you:

public static String cleanPreserveLineBreaks(String bodyHtml) {

    // get pretty printed html with preserved br and p tags
    String prettyPrintedBodyFragment = Jsoup.clean(bodyHtml, "", Whitelist.none().addTags("br", "p"), new OutputSettings().prettyPrint(true));
    // get plain text with preserved line breaks by disabled prettyPrint
    return Jsoup.clean(prettyPrintedBodyFragment, "", Whitelist.none(), new OutputSettings().prettyPrint(false));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM