使用jsoup来转义不允许的标签
我正在评估jsoup的function,它将清理(但不删除!)非白名单标签。 假设只允许标签,所以输入如下
foo bar baz
必须产生以下结果:
foo bar <script onLoad='stealYourCookies();'>baz</script>
我用jsoup看到以下问题/问题:
-
document.getAllElements()
始终采用,
和
。 是的,我可以调用
document.body().getAllElements()
但重点是我不知道我的源文件是完整的HTML文档还是只是正文 – 我希望结果的形状和forms与它进来了; - 如何将
...
替换为<script>...</script>
? 我只想用转义实体替换括号,并且不想改变任何属性等Node.replaceWith
听起来像是一种矫枉过正。 - 是否可以完全关闭漂亮的打印(例如插入新线等)?
或许我应该使用另一个框架? 到目前为止,我已经查看了htmlcleaner ,但是给出的示例并未建议我支持所需的function。
答案1
如何使用Jsoup加载/解析Document
? 如果你使用parse()
或connect().get()
jsoup将自动格式化你的html(插入html
, body
和head
标签)。 这样可以确保您始终拥有完整的Html文档 – 即使输入不完整。
假设您只想清理输入(无需处理),您应该使用clean()
而不是之前列出的方法。
示例1 – 使用parse()
final String html = "a"; System.out.println(Jsoup.parse(html));
输出:
a
输入html已完成,以确保您拥有完整的文档。
示例2 – 使用clean()
final String html = "a"; System.out.println(Jsoup.clean("a", Whitelist.relaxed()));
输出:
a
输入html被清理,而不是更多。
文档:
- Jsoup
答案2
方法replaceWith()
完全符合您的需要:
例:
final String html = ""; Document doc = Jsoup.parse(html); for( Element element : doc.select("script") ) { element.replaceWith(TextNode.createFromEncoded(element.toString(), null)); } System.out.println(doc);
输出:
<script>your script here</script>
或仅限身体 :
System.out.println(doc.body().html());
输出:
<script>your script here</script>
文档:
- Node.replaceWith(Node in)
- TextNode
答案3
是的, Jsoup.OutputSettings
prettyPrint()
方法Jsoup.OutputSettings
做到这一点。
例:
final String html = "your html here
"; Document doc = Jsoup.parse(html); doc.outputSettings().prettyPrint(false); System.out.println(doc);
注意:如果outputSettings()
方法不可用,请更新Jsoup。
输出:
your html here
文档:
- Document.OutputSettings.prettyPrint(boolean pretty)
答案4 (没有子弹)
没有! Jsoup是最好的 ,最有能力的 Html库之一!