使用DOMParser或innerHTML解析吗?

时间:2019-02-03 21:55:52

标签: javascript html innerhtml parsexml

这些示例之间有什么区别?为什么要使用一个示例而不是另一个示例来提高性能或浏览器兼容性?两者之间有不能做的事情吗?

txt="<address>"+
 "<street>Roble Ave</street>"+
  "<mtfcc>S1400</mtfcc>"+
  "<streetNumber>649</streetNumber>"+
  "<lat>37.45127</lat>"+
  "<lng>-122.18032</lng>"+
  "<distance>0.04</distance>"+
  "<postalcode>94025</postalcode>"+
  "<placename>Menlo Park</placename>"+
  "<adminCode2>081</adminCode2>"+
  "<adminName2>San Mateo</adminName2>"+
  "<adminCode1>CA</adminCode1>"+
  "<adminName1>California</adminName1>"+
  "<countryCode>US</countryCode>"+
 "</address>";
 
 var d = document.createElement('div')
 d.innerHTML = txt

console.log(d.getElementsByTagName("streetNumber")[0].childNodes[0].nodeValue);
console.log(d.getElementsByTagName("postalcode")[0].childNodes[0].nodeValue);

txt = "<address>" +
  "<street>Roble Ave</street>" +
  "<mtfcc>S1400</mtfcc>" +
  "<streetNumber>649</streetNumber>" +
  "<lat>37.45127</lat>" +
  "<lng>-122.18032</lng>" +
  "<distance>0.04</distance>" +
  "<postalcode>94025</postalcode>" +
  "<placename>Menlo Park</placename>" +
  "<adminCode2>081</adminCode2>" +
  "<adminName2>San Mateo</adminName2>" +
  "<adminCode1>CA</adminCode1>" +
  "<adminName1>California</adminName1>" +
  "<countryCode>US</countryCode>" +
  "</address>";

if (window.DOMParser) {
  parser = new DOMParser();
  xmlDoc = parser.parseFromString(txt, "text/xml");
} else // Internet Explorer
{
  xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
  xmlDoc.async = false;
  xmlDoc.loadXML(txt);
}


console.log(xmlDoc.getElementsByTagName("streetNumber")[0].childNodes[0].nodeValue);
console.log(xmlDoc.getElementsByTagName("postalcode")[0].childNodes[0].nodeValue);

http://jsfiddle.net/ub4mL80s/

http://jsfiddle.net/nm9yd0xz/1/

1 个答案:

答案 0 :(得分:2)

一个潜在的问题是,分配给新创建元素的innerHTML可以在txt内部执行内联处理程序:

const txt = `
 <address>
 <street>Roble Ave</street>
 ...
 </address>
 <img src="nosrc" onerror="alert('evil');">
 `;

const d = document.createElement('div')
d.innerHTML = txt

// navigate through d

如果txt可以包含任意数据,则存在安全风险。 DOMParser更安全,因为它没有此漏洞。

还请注意,您可以大大简化

d.getElementsByTagName("streetNumber")[0].childNodes[0].nodeValue

d.querySelector('streetNumber').textContent

还请注意,jQuery不参与任何操作-这只是Javascript。