user930514
user930514

Reputation: 927

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>

Suppose i want to parse the xml using javascript.

<!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>

The output is an alert box with message as Hello. I do not want the script to execute.

Instead of xmlDoc.getElementsByTagName("content")[0].childNodes[0].nodeValue; What can i do to get the output as :

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

Upvotes: 1

Views: 3783

Answers (2)

Vinod Srivastav
Vinod Srivastav

Reputation: 4255

I think you might have used this:

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

Upvotes: 0

Quentin
Quentin

Reputation: 943100

Don't document.write it - that treats it as HTML, not text.

Use createTextNode and then appendChild the result somewhere in the DOM.

Upvotes: 2

Related Questions