使用javascript解析xml与CDATA部分 - 阻止脚本执行

问题描述:

<?xml version="1.0" encoding="ISO-8859-1"?> 
<bookstore> 
<book category="cooking"> 
<page> 
<uri>http://www.somepage.com/page1.html</uri> 
<content><![CDATA[<script>alert("Hello");</script>]]></content> 
</page> 
<title lang="en">Everyday Italian</title> 
<author>Giada De Laurentiis</author> 
<year>2005</year> 
<price>30.00</price> 
</book> 
</bookstore> 

假设我想使用javascript解析xml。使用javascript解析xml与CDATA部分 - 阻止脚本执行

<!DOCTYPE html> 
<html> 
<body> 
<script> 
if (window.XMLHttpRequest) 
    {// code for IE7+, Firefox, Chrome, Opera, Safari 
    xmlhttp=new XMLHttpRequest(); 
    } 
else 
    {// code for IE6, IE5 
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
    } 
xmlhttp.open("GET","books.xml",false); 
xmlhttp.send(); 
xmlDoc=xmlhttp.responseXML; 

txt=xmlDoc.getElementsByTagName("content")[0].childNodes[0].nodeValue; 
document.write(txt); 
</script> 
</body> 
</html> 

输出是一个警报框,其中消息为Hello。我不希望脚本执行。

而不是xmlDoc.getElementsByTagName(“content”)[0] .childNodes [0] .nodeValue; 我能做些什么来得到的输出为:

<script>alert("Hello");</script> 
+0

'xmlDoc.getElementsByTagName( “内容”)[0] .childNodes [0] .nodeValue'是完美的。 UPVOTED! :) –

不要document.write它 - 这会将其作为HTML,而不是文字。

使用createTextNode然后appendChild结果在DOM中的某处。

我想你可能会使用这样的:

var config = new ActiveXObject("Microsoft.XMLDOM"); config.async = false; config.loadXML(xmlhttp.responseText); var read = config.selectNodes("//bookstore/book/page/content")[0]; alert(read);