2017-08-11 60 views
1

我將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

回答

2

正如我在我的評論中提到的,如果輸入是HTML,請不要試圖將其解析爲XML。 XML解析器必須對其輸入進行更嚴格的處理,例如使用不匹配的標記或多個根節點。

因此,下面應該工作:

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