在 XUL 文件中,欲於 <hbox id="aContainer"> 內動態插入 HTML 片段(含 <html:a>, <html:table> 等)。
<?xml version="1.0"?>
<window
xmlns="https://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
xmlns:html="https://www.w3.org/1999/xhtml"
...>
<vbox flex="1">
<hbox id="aContainer">
<html:a href="https://mozilla.org">Mozilla.org</html:a>
<html:table>
<html:tr><html:td>ok</html:td><html:td>ok</html:td></html:tr>
</html:table>
</hbox>
</vbox>
</window>
關鍵: 根元素宣告 xmlns:html="https://www.w3.org/1999/xhtml",HTML 元素全程加 html: 前綴。
錯誤代碼:
var dp = new DOMParser();
var newDOM = dp.parseFromString(htmlContent, "text/xml");
// 錯誤:XML Parsing Error: prefix not bound to namespace
document.getElementById('aContainer').appendChild(newDOM.documentElement);
htmlContent 字串中的 html:a、html:table 使用了 html: 前綴,但傳給 DOMParser 的字串未包含命名空間宣告,導致解析器無法解析前綴。
var htmlContent = '<div xmlns:html="https://www.w3.org/1999/xhtml">' +
'<html:a href="https://mozilla.org">Mozilla.org</html:a>' +
'<html:table>...</html:table>' +
'</div>';
var newDOM = dp.parseFromString(htmlContent, "application/xml");
將上述靜態寫法存為 test.xul,Firefox 3.5+ 可正常顯示。錯誤控制台可能出現:
Onload is not defined — 缺少 JS 函式定義document.createElementNS("https://www.w3.org/1999/xhtml", "a") 建立節點,避免字串解析坑