[英]parse xml with CDATA section using javascript - prevent execution of script
<?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。
<!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>
不要document.write
it - 將其視為 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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.