使用 Jsoup 清理时保留 <br> 标签

Preserving the <br> tags when cleaning with Jsoup

对于输入文字:

<p>Arbit string <b>of</b><br><br>text. <em>What</em> to <strong>do</strong> with it?

我运行下面的代码:

Whitelist list = Whitelist.simpleText().addTags("br");
// Some other code...
// plaintext is the string shown above
retVal = Jsoup.clean(plaintext, StringUtils.EMPTY, list,
            new Document.OutputSettings().prettyPrint(false));

我得到输出:

Arbit string <b>of</b>

text. <em>What</em> to <strong>do</strong> with it?

我不希望 Jsoup 将 <br> 标签转换为换行符,我希望保持原样。我该怎么做?

试试这个:

Document doc2deal = Jsoup.parse(inputText);
doc2deal.select("br").append("br"); //or append("<br>")

这对我来说不可重现。使用 Jsoup 1.8.3 和此代码:

String html = "<p>Arbit string <b>of</b><br><br>text. <em>What</em> to <strong>do</strong> with it?";
String cleaned = Jsoup.clean(html, 
        "", 
        Whitelist.simpleText().addTags("br"),
        new Document.OutputSettings().prettyPrint(false));
System.out.println(cleaned);

我得到以下输出:

Arbit string <b>of</b><br><br>text. <em>What</em> to <strong>do</strong> with it?

我猜你的问题一定出在其他地方。