简体   繁体   English

在解析 HTML 字符串时保留非 html 标记

[英]Preserve non-html tags while parsing the HTML string

I have been working in a project where the user need feature to parse the HTML data saved in the Database.我一直在一个项目中工作,用户需要功能来解析保存在数据库中的 HTML 数据。 I have used <div> and JSOUP to parse the value into HTML for eg:- <b>"Test"</b> .我使用<div>和 JSOUP 将值解析为 HTML 例如:- <b>"Test"</b> It works correctly to display - "Test" that text in that particular HTML format.它可以正常显示 - “测试”该特定 HTML 格式的文本。 But the problem arises when the text inside the tags get removed.但是当标签内的文本被删除时,问题就出现了。 For eg when I have angle bracket < > the text gets escaped in from the JSOUP <b>"Test 1 s< a test test 1<,tasa>"</b>例如,当我有尖括号 < > 文本从 JSOUP <b>"Test 1 s< a test test 1<,tasa>"</b>

I get result我得到结果

" Test 1 s " 测试 1 秒

The other text gets removed.其他文本被删除。 I need to display whole我需要显示整个

"Test 1 s< a test test 1<,tasa>". “测试 1 s< 测试测试 1<,tasa>”。

Any helps would be greatly appreciated.任何帮助将不胜感激。

Here is my code这是我的代码

def html = URLDecoder.decode(testValue.getAt('Test').replaceAll("%(?![0-9a-fA-F]{2})", "%25"),"UTF-8")
Jsoup.clean(html, Whitelist.basic())

UPDATED according to comments to support one level of nested elements根据评论更新以支持一级嵌套元素

to support recursive nested elements code must be reviewed为了支持递归嵌套元素,必须审查代码

groovy: groovy:

@Grab(group='org.jsoup', module='jsoup', version='1.11.3')
import org.jsoup.Jsoup
import org.jsoup.nodes.Document
import org.jsoup.nodes.TextNode

def html = '''
<html>
<title>my title</title>
<body>
<b>Test 1 s< a test test 1<,tasa> <foo>this</foo> zzz</b>
</body>
</html>'''

Document doc = Jsoup.parse(html)
def txt = doc.select('html body b').first()?.childNodes()
             .collect{e-> e instanceof TextNode ? e.text() : e.toString() }.join()

println txt

prints印刷

Test 1 s< a test test 1<,tasa> <foo>
 this
</foo> zzz

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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