【发布时间】:2018-08-16 14:18:38
【问题描述】:
我在 utf-8 中有 html 输入。在此输入中,重音字符显示为 html 实体。例如:
<html>
<head>
<META http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>árvíztűrő<b</body>
</html>
我的目标是通过在 Java 中尽可能用 utf-8 字符替换 html 实体来“规范化”html。换句话说,替换所有实体除了 &lt; &gt; &amp; &quot; &apos;。
目标:
<html>
<head>
<META http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>árvíztűrő<b</body>
</html>
我需要它以便更容易在测试中比较 html,并且更容易用肉眼阅读(大量转义的重音字符使其难以阅读)。
我不关心 cdata 部分(输入中没有 cdata)。
我尝试过 JSOUP (https://jsoup.org/) 和 Apache 的 Commons Text (https://commons.apache.org/proper/commons-text/) 均未成功:
public void test() throws Exception {
String html =
"<html><head><META http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">" +
"</head><body>árvíztűrő<b</body></html>";
// this is not good, keeps only the text content
String s1 = Jsoup.parse(html).text();
System.out.println("s1: " + s1);
// this is better, but it unescapes the < which is not what I want
String s2 = StringEscapeUtils.unescapeHtml4(html);
System.out.println("s2: " + s2);
}
StringEscapeUtils.unescapeHtml4() 几乎是我所需要的,但不幸的是它使
<body>árvíztűrő<b</body>
我该怎么做?
【问题讨论】:
标签: java html escaping html-entities