Load an XML File and Obtain Child Element Values
The following sample loads the BookSample.xml file from the File Cabinet, iterates through the individual book nodes, and accesses the child node values.
Note:
This sample script uses the require
function so that you can copy it into the SuiteScript Debugger and test it. You must use the define
function in an entry point script (the script you attach to a script record and deploy). For more information, see SuiteScript 2.x Script Basics and SuiteScript 2.x Script Types.
/**
* @NApiVersion 2.x
* @NScriptType Suitelet
*/
require(['N/xml', 'N/file'], function(xml, file) {
return {
onRequest: function(options) {
var sentence = '';
var xmlFileContent = file.load('SuiteScripts/BookSample.xml').getContents();
var xmlDocument = xml.Parser.fromString({
text: xmlFileContent
});
var bookNode = xml.XPath.select({
node: xmlDocument,
xpath: '//b:book'
});
for (var i = 0; i < bookNode.length; i++) {
var title = bookNode[i].firstChild.nextSibling.textContent;
var author = bookNode[i].getElementsByTagName({
tagName: 'b:author'
})[0].textContent;
sentence += 'Author: ' + author + ' wrote ' + title + '.\n';
}
options.response.write(sentence);
}
};
});
This script produces the following output when used with the BookSample.xml file:
Author: Giada De Laurentiis wrote Everyday Italian.
Author: J K. Rowling wrote Harry Potter.
Author: James McGovern wrote XQuery Kick Start.
Author: Erik T. Ray wrote Learning XML.