myData.xml
<?xml version='1.0'?>
<root>
<data>
<animal>Lion</animal>
<habitat>jungle</habitat>
<type>mammal</type>
<eatingHabit>Carnivore</eatingHabit>
</data>
<data>
<animal>Deer</animal>
<habitat>jungle</habitat>
<type>mammal</type>
<eatingHabit>Herbivore</eatingHabit>
</data>
</root>
myData.html
<!DOCTYPE html>
<html>
<body>
<h1>Adding CDATA </h1>
<script>
function loadFile(name){
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",name,false);
xmlhttp.send();
return xmlhttp.responseXML;
}
xmlDoc = loadFile("myData.xml");
x=xmlDoc.getElementsByTagName("data");
for(i=0; i<x.length; i++){
newCDATA=xmlDoc.createCDATASection("Carnivorous:Herbivorous ratio");
x[i].appendChild(newCDATA);
}
for (i=0; i<x.length; i++)
{
document.write(x[i].getElementsByTagName("animal")[0].childNodes[0].nodeValue);
document.write("-" + x[i].lastChild.nodeValue);
cdataNode = x[i].lastChild.nodeValue;
document.write(" - Length of CDATA is: " + cdataNode.length + "<br/>");
}
for (i=0; i<x.length; i++)
{
document.write("<br/> Replaced CDATA <br/>");
cdataNode = x[i].lastChild;
cdataNode.replaceData(0,29, "Herbivorous:Carnivorous ratio");
// document.write(x[i].lastChild.nodeValue;)
document.write(x[i].getElementsByTagName("animal")[0].childNodes[0].nodeValue);
document.write("-" + x[i].lastChild.nodeValue);
}
</script>
</body>
</html>
Output of the example above:
Adding CDATA
Lion-Carnivorous:Herbivorous ratio - Length of CDATA is: 29
Deer-Carnivorous:Herbivorous ratio - Length of CDATA is: 29
Replaced CDATA
Lion-Herbivorous:Carnivorous ratio
Replaced CDATA
Deer-Herbivorous:Carnivorous ratio
Comments
No comments have been made yet.
Please login to leave a comment. Login now