我用 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
它显示为
,但是 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>
(其实是函数结果,不是异常!很奇葩的解法(:.)
我试过了 &nbsp;
同样,这在没有 <parsererror>
的情况下成功了标记,但被读回为 " "
字符串,而不是 UNICODE 160 代码点。
可能其他 HTML 规范字符也会受到影响。
我应该在哪里以及如何转义/替换特殊的 HTML 字符以获得完全相同的 dom
和原来一样?
提前致谢。
最佳答案
正如@forty-two 所建议的,XMLSerializer
解决了这个问题:
var xml = '<xml xmlns="http://www.w3.org/1999/xhtml">'
+ (new XMLSerializer).serializeToString(dom)
+ '</xml>'
这会将不间断空格字符直接插入到结果中。 (没有“&”字符。) 读取端无需更改。 谢谢。
关于javascript - 将特殊的 HTML 字符插入 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58267037/