Javascript DOMParser忽略/超级解析错误

问题描述:

我将api转换为html到dom元素,以便我可以解析xml内容。内容的一个例子:Javascript DOMParser忽略/超级解析错误

var html = '<p><a href="https://www.nytimes.com/2017/07/16/movies/george-romero-dead.html?_r=0" target="_blank">George Romero</a>, the highly influential auteur filmmaker and giant of horror and independent cinema passed away on July 16. He was 77 years old.</p>'; 

var convertHtmlToDom = function(html) { 
    var parser = new DOMParser(); 
    return parser.parseFromString(html, "text/xml"); 
} 

除非我得到这个错误:

<parsererror xmlns="http://www.w3.org/1999/xhtml" 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 2 at column 1: Extra content at the end of the document 
</div><h3>Below is a rendering of the page up to the first error.</h3></parsererror> 

我怎么能抑制或忽略这些错误?

+0

不解析为XML。尝试'parser.parseFromString(html,'text/html');'。 – Phylogenesis

正如我在我的评论中提到的,如果输入是HTML,请不要试图将其解析为XML。 XML解析器必须对其输入进行更严格的处理,例如使用不匹配的标记或多个根节点。

因此,下面应该工作:

parser.parseFromString(html, 'text/html');