如何在 JavaScript 中为 XML 创建有效的字符串?

发布于 2024-09-03 12:48:28 字数 201 浏览 15 评论 0原文

我正在寻找一个函数,可以根据需要将字符串转换为带有 xml 实体的 xml 字符串。类似 PHP 中的 htmlentities 但适用于 XML 和 Javascript。

感谢您的帮助!

I'm looking for a function to convert a string to the xml string with xml entities where needed. Something like htmlentities in PHP but for XML and in Javascript.

Thank you for any help!

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

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

发布评论

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

评论(1

幼儿园老大 2024-09-10 12:48:28

没有任何内置的东西(除了 innerHTML 序列化,这对于这个目的来说是超级狡猾的),你必须自己编写它,例如:

function encodeXml(s) {
    return (s
        .replace(/&/g, '&').replace(/"/g, '"').replace(/'/g, ''')
        .replace(/</g, '<').replace(/>/g, '>')
        .replace(/\t/g, '	').replace(/\n/g, '
').replace(/\r/g, '
')
    );
}

这是一个安全的最大化转义函数:

  • 它始终会编码 "' 和 tab/CR/LF 字符,尽管它们只需要在属性值中转义,其中该特定引号字符被用作分隔符。

  • 始终对 > 进行编码,尽管实际上仅当文本内容中的 ]]> 序列的一部分时才需要转义。

如果您不需要这些属性,您可以删除不需要的 replace (例如,很少需要将 tab/CR/LF 放入属性值中)。

如果您需要生成与 HTML 兼容的 XHTML,请使用 ' 而不是 '(如果需要转义)。

一般来说,您应该避免 htmlentities 并使用 htmlspecialchars 代替,因为 htmlentities 不必要地将所有非 ASCII 字符编码为 HTML 实体引用,这也具有如果您没有给它正确的 $charset 参数,则会产生搞乱文本的副作用。

There's nothing built-in (except innerHTML serialisation which is super-dodgy for this purpose), you'd have to write it yourself, eg.:

function encodeXml(s) {
    return (s
        .replace(/&/g, '&').replace(/"/g, '"').replace(/'/g, ''')
        .replace(/</g, '<').replace(/>/g, '>')
        .replace(/\t/g, '	').replace(/\n/g, '
').replace(/\r/g, '
')
    );
}

This is a maximalist escaping function for safety:

  • it will always encode ", ' and tab/CR/LF characters though they only need to be escaped in an attribute value, where that particular quote character is being used as a delimiter.

  • it will always encode > though this only actually needs to be escaped when part of the ]]> sequence in text content.

If you don't need these properties you can remove the replace​s you don't need (it's pretty rare to need to put tab/CR/LF in an attribute value, for example).

If you need to produce HTML-compatible XHTML, use ' instead of ' if you need that escape.

In general you should avoid htmlentities and use htmlspecialchars instead, as htmlentities unnecessarily encodes all non-ASCII characters as HTML entity references, which also has the side-effect of screwing up your text if you don't give it the right $charset parameter.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文