In cases when you are writing server-side codes, you may need to manipulate XML files. During such situations you may find difficulties in doing it since Jaggery documentation doesn’t contain sufficient information on that. In this article I’m going to mention on how to achieve some XML related manipulations based on the experience I got.
For the purpose of explanation I’ll use the following XML document in the rest of this article.
<task name="Task1" xmlns="http://www.wso2.org/products/wso2commons/tasks"> <trigger count="1" interval="100"/> <property xmlns:task="http://www.wso2.org/products/wso2commons/tasks" name="Params"> <salesforceInfo xmlns=""> <salesforce.username>buddhima</salesforce.username> <salesforce.batchSize>20</salesforce.batchSize> </salesforceInfo> </property> </task>
Reading from a file
Let’s assume the XML content is in a file called “task.xml”. So initially you need to read from there and form an XML object out of it.
var file = new File("task.xml"); // Here open file just to read file.open("r"); // Read task xml file and convert to xml object var taskFile = file.readAll(); var taskFileXml = new XML(taskFile); // Close the file file.close(); // Any thing you want to do with taskFileXml object goes here ...
From here onwards I consider “taskFileXml” is an object with the XML given in Sample XML.
Changing a value inside XML tags
If you want to change content inside “salesforce.username”, you can do it as follows:
Note that ‘..*::’ notation will find out the first XML element contains ‘salesforce.username’ for you.
Changing attribute of the <task>
Following code will change the name attribute inside task element.
Changing attributes inside <task>
To change the ‘interval’ attribute of you can use the following:
Saving XML file
To save modified ‘taskFileXml’ object, following code can be used.
var file = new File("newtask.xml"); file.open("w"); // At the end write all the content to newtask xml file file.write(taskFileXml); file.close();
Convert XML object to a JSON object
It may be quite handy to use JSON objects rather than XML objects. By engaging ‘util’ module with Jaggery, you can achieve this:
// Translate xml to json using jaggery new util-xml module var utils = require('utils').xml; var taskConvertedJson = utils.convertE4XtoJSON(taskFileXml);
Most of these operations are extracted from E4X documentation, which is deprecated but using in JaggeryJS. In this article I tried to provide concrete use-cases with XML manipulations and hope will help in your Jaggery App.
 JaggeryJS Documentation : http://jaggeryjs.org/documentation.jag
 Jaggery XML : http://jaggeryjs.org/documentation.jag?api=xml
 E4X Quick Start : http://wso2.com/project/mashup/0.2/docs/e4xquickstart.html
 E4X Specification : http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-357.pdf