Posts tagged with “XML”
- All (1)
- Entries (1)
- Links (0)
- Photos (0)
Introducing node-xml2object
Recently, I’ve been playing around with node.js, because, well, it’s really, really cool. I found myself wanting to parse XML into a Javascript object, but I couldn’t find any existing modules that did what I needed. So, I went ahead and made my own, node-xml2object. It’s dead simple to use, and I hope others find it as useful as I have. For example, imagine you have some XML like this:
<root>
<videos total="2">
<video id="1" length="20">
<title>Video 1</title>
</video>
<video>
<title>Video 2</title>
</video>
</videos>
</root>
Here’s how you would access it as an object, assuming the XML is stored in the variable xml:
var sys = require('sys'),
xml2object = require('./xml2object');
var response = xml2object.parseString(xml);
response.addCallback(function(obj) {
// To output a simple value, just use as an object
// Since there are 2 video elements under <videos>, it's stored as an array
sys.puts(obj.root.videos.video[1].title) // outputs "Video 2"
// attr(key) returns the value for attribute with name "key"
sys.puts(obj.root.videos.attr("total")) // outputs "2"
// attrs() returns an object of all attributes
sys.puts(obj.root.videos.video[0].attrs().id); // outputs "1"
});
Node-xml2object depends on the node-xml module, and the tests use ntest. Right now, I’m embedding them as Git submodules, but I’m planning on changing that in the near future, since it’s pretty messy this way. The source code is licensed under the MIT license, so feel free to use it however you’d like. I’m pretty happy with where it’s at now, but if anyone would like to fork it and improve things, go for it!
