你应该让浏览器来完成“繁重的工作”;显然,浏览器可以解析 HTML - 毕竟,它应该如何向我们显示网页呢?您可以通过设置使用 JavaScript 让浏览器为您解析 HTML.innerHTML
将某些 dom 节点添加到 HTML 字符串中,或者使用.insertAdjacentHTML
。然后,您已将 HTML 字符串转换为 DOM 节点树,即对其进行了解析。
并且有浏览器内置的方法可以将 DOM 树转换为 XHTML 字符串。您只需以编程方式创建一个 XHTML 文档,然后向其中添加任何 DOM 树(可以来自 HTML(非 XHTML)文档,这完全没问题):.appendChild
,然后是.outerHTML
and .innerHTML
DOM 树(现在有一个 XHTML 文档作为所有者文档)的方法将给出 XHTML。
如果您从 DOM 节点开始,则可以使用以下 2 个函数:
var nsx = "http://www.w3.org/1999/xhtml";
function outerXHTML(node){
var xdoc = document.implementation.createDocument(nsx, 'html');
xdoc.documentElement.appendChild(node);
return node.outerHTML;
}
function innerXHTML(node){
var xdoc = document.implementation.createDocument(nsx, 'html');
xdoc.documentElement.appendChild(node);
return node.innerHTML;
}
(请注意,该节点将属于新创建的 XHTML 文档,因此它将从原始文档中消失。如果它应该保留在那里,请在调用上述函数之一之前克隆它。)
如果您从字符串开始,我们只需在调用上面之前设置新创建的节点的innerHTML。为了您的方便,这里有一个片段。有3个例子。 2 个用于 html 到 xhtml,1 个用于 xhtml 到 html。
function html2xhtml(html){
var nsx = "http://www.w3.org/1999/xhtml";
var body = document.createElement('body');
body.innerHTML = html;
var xdoc = document.implementation.createDocument(nsx, 'html');
xdoc.documentElement.appendChild(body);
return body.innerHTML;
}
function xhtml2html(xhtml){
var body = document.createElement('body');
body.innerHTML = xhtml;
var doc = document.implementation.createHTMLDocument();
doc.documentElement.appendChild(body);
return body.innerHTML;
}
var html1 = '<div>lorem<img>ipsum<img>dolor sit amet<br></div>';
var html2 = '<ul><li><svg><rect width="100" height="100"></rect></svg></li></ul>';
var html3x = '<img />';
var node1 = document.getElementById('node1');
var node1x = document.getElementById('node1x');
var node2 = document.getElementById('node2');
var node2x = document.getElementById('node2x');
var node3 = document.getElementById('node3');
var node3x = document.getElementById('node3x');
node1.textContent = html1;
node2.textContent = html2;
node3x.textContent = html3x;
node1x.textContent = html2xhtml(html1);
node2x.textContent = html2xhtml(html2);
node3.textContent = xhtml2html(html3x);
html<br><pre id='node1'></pre>xhtml<br><pre id='node1x'></pre><hr>
html<br><pre id='node2'></pre>xhtml<br><pre id='node2x'></pre><hr><hr>
xhtml<br><pre id='node3x'></pre>html<br><pre id='node3'></pre>
旧版本代码 https://jsfiddle.net/mathheadinclouds/2gtq6vLd/4/
您也可以使用 XMLSerializer 来完成 https://jsfiddle.net/mathheadinclouds/2gtq6vLd/11/(为了toString
part notfromString 部分),信用@Kaiido。