如何在 Java 中将非特殊字符编码为 HTML 实体

发布于 2024-12-08 17:30:52 字数 324 浏览 7 评论 0原文

以下代码:

org.apache.commons.lang.StringEscapeUtils.unescapeHtml("Hello World");

给出:

Hello World

但我想知道如何从“Hello World”返回解码后的字符串。我尝试过 escapeHtml 方法,但这只编码特殊字符。

The following code:

org.apache.commons.lang.StringEscapeUtils.unescapeHtml("Hello World");

gives:

Hello World

But I'd like to know how to get back to the decoded string from "Hello World". I have tried the escapeHtml method, but this only encodes special characters.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

彩虹直至黑白 2024-12-15 17:30:52

但我想知道如何从“Hello World”返回解码后的字符串。我尝试过 escapeHtml 方法,但这没有任何用处。

关于“任何有用的东西”不正确;如果您的测试字符串包含 HTML 特殊字符,例如 <、>、&,该函数会将其转换为 < >和&; (并将其他上层ISO8859-1代码更改为实体)。

如果您需要将其编码回 Unicode 实体格式,只需迭代字符串代码点即可:

for (int i = 0; i < str.length(); i++)
    System.out.print("&#" + str.codePointAt(i) + ";");

But I'd like to know how to get back to the decoded string from "Hello World". I have tried the escapeHtml method, but this doesn't do anything useful.

Not true about "anything useful"; if your test string contained HTML special characters like <,>,&, the function would've turned it into < > and & (and change other upper ISO8859-1 codes into entities).

If you need to encode it back to Unicode entity format, just iterate through the String codepoints:

for (int i = 0; i < str.length(); i++)
    System.out.print("&#" + str.codePointAt(i) + ";");
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文