如何在 JavaScript 中为 XML 创建有效的字符串?
我正在寻找一个函数,可以根据需要将字符串转换为带有 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
没有任何内置的东西(除了
innerHTML
序列化,这对于这个目的来说是超级狡猾的),你必须自己编写它,例如:这是一个安全的最大化转义函数:
它始终会编码
"
、'
和 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.: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 usehtmlspecialchars
instead, ashtmlentities
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.