topical media & game development
basic-xml-11-AlterValue.htm / htm
<html>
<head>
<title>Retrieve a named node and change its value</title>
</head>
<body>
<script language="JScript" type="text/javascript">
try {
var strXML = "<?xml version='1.0' ?><Book><Chapter number='1'>This is Chapter 1.</Chapter><Chapter number='2'>This is Chapter 2.</Chapter><Chapter number='3'>This is the original Chapter 3.</Chapter></Book>"
var objXMLDOM = new ActiveXObject("Msxml2.DOMDocument.3.0");
objXMLDOM.loadXML(strXML);
alert(objXMLDOM.xml); // Show the original XML
// First use the insertBefore(newChild, refChild) method to insert
// another Chapter element
objOriginalThird = objXMLDOM.documentElement.childNodes.item(2);
alert(objOriginalThird.firstChild.nodeValue); // Confirm we have the right Chapter node
var strNewText = "This is the new Chapter 3.";
var objTextNode = objXMLDOM.createTextNode(strNewText);
var objToBeInserted = objXMLDOM.createElement("Chapter");
objToBeInserted.appendChild(objTextNode);
objXMLDOM.documentElement.insertBefore(objToBeInserted, objOriginalThird);
alert("A Chapter element has been inserted before the original third Chapter.\n\n" + objXMLDOM.xml); // Display intermediate state of XML
// Remove and replace number attribute on old Chapter 3
var objNewNumberAttribute = objXMLDOM.createAttribute("number");
objNewNumberAttribute.nodeValue = 4;
var mapChapterAttributes = objXMLDOM.documentElement.lastChild.attributes ;
mapChapterAttributes.removeNamedItem("number");
mapChapterAttributes.setNamedItem(objNewNumberAttribute) ;
alert("The old number attribute of the final chapter has been removed and a new number \nattribute with value of 4 replaces it\n\n" + objXMLDOM.xml); // Display intermediate state of the XML
// Add a number attribute to the inserted Chapter 3
var objAddedNumberAttribute = objXMLDOM.createAttribute("number");
objAddedNumberAttribute.nodeValue = 3;
mapChapterAttributes = objXMLDOM.documentElement.childNodes.item(2).attributes;
mapChapterAttributes.setNamedItem(objAddedNumberAttribute);
alert("A number attribute has been added (with value of 3) to the inserted Chapter element.\n\n" + objXMLDOM.xml);
}
catch (e)
{
alert("An exception has occurred.");
}
</script>
</body>
</html>
(C) Æliens
20/2/2008
You may not copy or print any of this material without explicit permission of the author or the publisher.
In case of other copyright issues, contact the author.