Javascript XML

From FreeSWITCH Wiki
Jump to: navigation, search

(not a real document, just an example)

var xmldata = new XML("<mydata><item>this is my data</item><item>this is also my data</item></mydata>");
for each (item in xmldata.item) {
    console_log("ITEM: " + item + "\n");
} 

If using the new mod_v8 module, the XML support is built upon the XML features inside FS, since Google V8 doesn't have this built-in like Spidermonkey do.

Some example code:

// Tell JS we wan't to load the XML class features.
use('XML');

// Load and parse an XML string.
var xml = new XML('<xml><test>TestData</test><test>TestData 2<test2>test</test2></test></xml>');

// Get the first child named 'test'
var child = xml.getChild('test');

if (child) {
    consoleLog('info', 'XML child name: ' + child.name + ', data: ' + child.data);
}

// Get next child of the same name and same level
var nextChild = child.next();

if (nextChild) {
    consoleLog('info', 'XML child name: ' + nextChild.name + ', data: ' + nextChild.data);
}

// Create a new child
var newChild = xml.addChild('NewTest');

// Set some data to it
newChild.data = 'new data';

// Set an attribute
newChild.setAttribute('firstattr', 'myvalue');

// Print the attribute
consoleLog('info', 'XML newChild attrbute firstattr: ' + newChild.getAttribute('firstattr'));

// Remove the first child 'test'
child.remove();

// Log the entire XML
consoleLog('info', 'Full XML ::\n' + xml.serialize());

See Also