Jsoup.clean没有添加html实体

aio*_*obe 26 html java html-entities jsoup

我正在<script>通过使用来清除不需要的HTML标记(例如)中的一些文本

String clean = Jsoup.clean(someInput, Whitelist.basicWithImages());
Run Code Online (Sandbox Code Playgroud)

问题是,它取代例如å&aring;(这会导致麻烦的我,因为它不是"纯XML").

例如

Jsoup.clean("hello å <script></script> world", Whitelist.basicWithImages())
Run Code Online (Sandbox Code Playgroud)

产量

"hello &aring;  world"
Run Code Online (Sandbox Code Playgroud)

但我想

"hello å  world"
Run Code Online (Sandbox Code Playgroud)

有没有一种简单的方法来实现这一目标?(比转换&aring;å结果更简单.)

小智 34

您可以配置Jsoup的转义模式:使用EscapeMode.xhtml将为您提供输出w/o实体.

这是一个完整的片段,接受str输入,并使用Whitelist.simpleText()以下方法清除它:

// Parse str into a Document
Document doc = Jsoup.parse(str);

// Clean the document.
doc = new Cleaner(Whitelist.simpleText()).clean(doc);

// Adjust escape mode
doc.outputSettings().escapeMode(EscapeMode.xhtml);

// Get back the string of the body.
str = doc.body().html();
Run Code Online (Sandbox Code Playgroud)

  • 不知怎的,它对&bull不起作用; 实体. (3认同)

Fra*_*ski 10

Jsoup的网站上已有功能请求.您可以通过添加新的空Map和新的转义类型来自己扩展源代码.如果您不想这样做,可以使用apache commons中的StringEscapeUtils.

public static String getTextOnlyFromHtmlText(String htmlText){
    Document doc = Jsoup.parse( htmlText );
    doc.outputSettings().charset("UTF-8");
    htmlText = Jsoup.clean( doc.body().html(), Whitelist.simpleText() );
    htmlText = StringEscapeUtils.unescapeHtml(htmlText);
    return htmlText;
}
Run Code Online (Sandbox Code Playgroud)

  • @frandevel这将是一个非常糟糕的主意.如果输入是"&lt; script&gt; alert('Hello');&lt;/script&gt;`,您实际上会注入不安全的HTML并允许XSS攻击. (2认同)

ers*_*ril 5

&bmoc 的回答工作正常,但您可以使用更短的解决方案:

// Clean html
Jsoup.clean(someInput, "yourBaseUriOrEmpty", Whitelist.simpleText(), new OutputSettings().escapeMode(EscapeMode.xhtml))
Run Code Online (Sandbox Code Playgroud)