【问题标题】:Inserting special HTML characters into XML将特殊的 HTML 字符插入 XML
【发布时间】:2020-02-04 14:24:57
【问题描述】:

我在 JavaScript 中用这个表达式生成一个 XML 字符串:

var xml = '<xml xmlns="http://www.w3.org/1999/xhtml">' + dom.outerHTML + '</xml>'

dom 是文档树中的某个节点。)

后来我读了一遍:

... = (new DOMParser).parseFromString(xml, "text/xml");

通常它可以正常工作,但当dom 中的一个字段包含不间断空格字符时会失败,该字符是使用 Alt+0160 手动键入的。 在dom.outerHTML 中,它显示为&amp;amp;nbsp;,但parseFromString 函数返回:

<xml xmlns="http://www.w3.org/1999/xhtml">
    <parsererror style="display: block; white-space: pre; border: 2px solid #c77; padding: 0 1em 0 1em; margin: 1em; background-color: #fdd; color: black">
        <h3>This page contains the following errors:</h3>
        <div style="font-family:monospace;font-size:12px">error on line 1 at column 139: Entity 'nbsp' not defined↵</div>
        <h3>Below is a rendering of the page up to the first error.</h3>
    </parsererror>
    ...
</xml>

(其实是函数结果,不是异常!很奇怪的解决方法(:.)

我也试过&amp;amp;nbsp;,没有&lt;parsererror&gt;标签就成功了,但被读回为"&amp;nbsp;"字符串,而不是UNICODE 160代码点。

可能其他 HTML 规范字符也会受到影响。

我应该在哪里以及如何转义/替换特殊的 HTML 字符以恢复与原来完全相同的dom

提前致谢。

【问题讨论】:

标签: javascript html xml dom escaping


【解决方案1】:

正如@forty-2 建议的那样,XMLSerializer 解决了这个问题:

var xml = '<xml xmlns="http://www.w3.org/1999/xhtml">' 
  + (new XMLSerializer).serializeToString(dom) 
  + '</xml>'

这会将不间断空格字符直接插入结果中。 (没有“&”字符。) 读取端无需更改。 谢谢。

【讨论】:

    猜你喜欢
    • 2016-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-14
    • 1970-01-01
    • 2011-11-07
    • 1970-01-01
    相关资源
    最近更新 更多