XML parsing in ECMAScript¶
When using ECMAScript and Duktape the plugins need to rely on Movian's XML parser. To access do:
var XML = require('showtime/xml');
To parse a string as XML then do as this tiny example:
var doc = XML.parse('<foo><bar baz="123">meh</bar></foo>');
Accessing nodes in the element is easy, just dereference properties
console.log(doc.foo.bar); // prints 'meh'
Attributes are prepared with an 'at' (@) sign an thus needs to be accessed using the array operator:
console.log(doc.foo.bar["@baz"]); // prints '123'
Let's step it up by creating a more complicated document
var doc2 = XML.parse('<result>' + '<alpha>1</alpha>' + '<beta>2</beta>' + '<gamma>3</gamma>' + '<delta>4</delta>' + '</result>');
Nodes can be iterating using the standard ECMAScript enumeration technique:
for(v in doc2.result) { print(v + " = " + doc2.result[v]); }
will print
alpha = 1 beta = 2 gamma = 3 delta = 4
Iterating over nodes which have the same name is possible using the filterNodes() method, see the following example:
var doc3 = XML.parse('<dataset>' + '<data>foo</data>' + '<data>bar</data>' + '<data>baz</data>' + '<data>quux</data>' + '<metadata>quuz</metadata>' + '</dataset>'); var all_the_data = doc3.dataset.filterNodes('data'); for(var i = 0; i < all_the_data.length; i++) { var data = all_the_data[i]; print(i + ". " + data); }
Will print
0. foo 1. bar 2. baz 3. quux
No surprises really.
For some extra info and reference, here is a diff of the change needed to convert Movian's Headweb plugin from JavaScript (SpiderMonkey) to ECMAScript (Duktape)
https://github.com/andoma/showtime-plugin-headweb/commit/dfa43609fde79a65834e3fca7f7ca696fb7f8805