The replaceChild method replaces a child node with another. This method has two required parameters. The first is the new node and the second is the child node that will be replaced.
Sample script:
//declare a variable that will hold the XML in the form of a string
var xmlStringVar = '<?xml version="1.0" encoding="ISO-8859-1"?>';
xmlStringVar = xmlStringVar + '<bookstore>';
xmlStringVar = xmlStringVar + '<book category="cooking">';
xmlStringVar = xmlStringVar + '<title lang="en">Everyday Italian</title>';
xmlStringVar = xmlStringVar + '<author>Giada De Laurentiis</author>';
xmlStringVar = xmlStringVar + '<year>2005</year>';
xmlStringVar = xmlStringVar + '<price>30.00</price>';
xmlStringVar = xmlStringVar + '<title lang="en">French Today</title>';
xmlStringVar = xmlStringVar + '<author>Giada De Laurentiis</author>';
xmlStringVar = xmlStringVar + '<year>2005</year>';
xmlStringVar = xmlStringVar + '<price>30.00</price>';
xmlStringVar = xmlStringVar + '</book>';
xmlStringVar = xmlStringVar + '</bookstore>';
//convert the string data into XML using nlapiStringToXML
var xmlData = nlapiStringToXML(xmlStringVar);
//declare a variable that will hold the xpath
path = "/bookstore/book/title";
//create a new book node
var newBookNode = xmlData.createElement("book");
var newTitleNode = xmlData.createElement("title");
var newTitleNodeValue = xmlData.createTextNode("German Delight");
var newAuthorNode = xmlData.createElement("author");
var newAuthorNodeValue = xmlData.createTextNode("Jackson Gibbs");
var newYearNode = xmlData.createElement("year");
var newYearNodeValue = xmlData.createTextNode("2002");
var newPriceNode = xmlData.createElement("price");
var newPriceNodeValue = xmlData.createTextNode("50.00");
newTitleNode.appendChild(newTitleNodeValue);
newAuthorNode.appendChild(newAuthorNodeValue);
newYearNode.appendChild(newYearNodeValue);
newPriceNode.appendChild(newPriceNodeValue);
newBookNode.appendChild(newTitleNode);
newBookNode.appendChild(newAuthorNode);
newBookNode.appendChild(newYearNode);
newBookNode.appendChild(newPriceNode);
//set the node that will be replaced
var existingBookPath = "/bookstore/book";
var nodeReplaced = nlapiSelectNode(xmlData, existingBookPath);
//replace the child node using replaceChild
var xmlElements = nlapiSelectNode(xmlData, "/bookstore");
xmlElements.replaceChild(newBookNode,nodeReplaced);
//declare a variable that will hold the selected node
var nodeData = new Array();
nodeData = nlapiSelectNodes(xmlData, path );
//print the values of the selected nodes
for(var i = 0; i < nodeData.length; i++){
nlapiLogExecution('DEBUG','nlapiSelectNodes(xmlData, path)', nodeData[i].firstChild.nodeValue);
}
-----
Result:
User should get 'German Delight'.
No comments:
Post a Comment