Java 用Jsoup替换一些HTML属性,而不更改其余的输入
我处理传入的html文本块,如下所示:Java 用Jsoup替换一些HTML属性,而不更改其余的输入,java,html,regex,jsoup,Java,Html,Regex,Jsoup,我处理传入的html文本块,如下所示: String html = "<p>Some text here with already existing tags and it's escaped symbols.\n" + " More text here:<br/>\\r\\n---<br/>\\r\\n" + " <img src=\"/attachments/
String html = "<p>Some text here with already existing tags and it's escaped symbols.\n" +
" More text here:<br/>\\r\\n---<br/>\\r\\n" +
" <img src=\"/attachments/a0d4789a-1575-4b70-b57f-9e8fe21df46b\" sha256=\"2957635fcf46eb54d99f4f335794bd75a89d2ebc1663f5d1708a2fc662ee065c\"></a>" +
" It was img tag with attr to replace above</p>\\r\\n\\r\\n<p>More text here\n" +
" and here.<br/>\\r\\n---</p>";
Document doc = Jsoup.parse(html);
Elements elementsByAttribute = doc.select("img[src]");
elementsByAttribute.forEach(x -> x.attr("src", "/usr/myfolder/" + x.attr("sha256") + ".zip"));
但有一个问题。传入文本已经有一些需要保留的格式、html标记、转义等。但是Jsoup删除标记/添加标记/取消场景/转义,并对原始输入进行一些其他修改
例如,System.out.println(doc)
或System.out.println(doc.html())代码>提供了以下信息:
<html>
<head></head>
<body>
<p>Some text here with already existing tags and it's escaped symbols. More text here:<br>\r\n---<br>\r\n <img src="/usr/myfolder/2957635fcf46eb54d99f4f335794bd75a89d2ebc1663f5d1708a2fc662ee065c.zip" sha256="2957635fcf46eb54d99f4f335794bd75a89d2ebc1663f5d1708a2fc662ee065c"> It was img tag with attr to replace above</p>\r\n\r\n
<p>More text here and here.<br>\r\n---</p>
</body>
</html>
Some text here with already existing tags and it's escaped symbols. More text here: \r\n--- \r\n It was img tag with attr to replace above\r\n\r\n More text here and here. \r\n---
我的标签在这里被删除,it';s
被转义到它再次是
我尝试了其他一些Jsoup特性,但没有找到解决这个问题的方法
问题:有没有办法在不改变其他标记的情况下,用Jsoup只替换一些属性?也许有别的图书馆可以做这个?或者我唯一的方法是regex?根据,.parse()
将生成“sane HTML”,因此它假设您想要添加头部和身体。你不妨试一试。您还可以尝试doc.body()
同样的问题仍然存在,您必须深入研究API并确定JSOUP是否适合您的需要。JSOUP显然做出了各种假设,因此如果这些假设对您不好,那么您需要找到不同的库。根据,.parse()
将生成“sane HTML”,因此它假设您希望在头部和身体中添加。你不妨试一试。您还可以尝试doc.body()
同样的问题仍然存在,您必须深入研究API并确定JSOUP是否适合您的需要。JSOUP显然做出了各种各样的假设,所以如果这些假设对您不利,那么您需要找到一个不同的库。