Oct 2012

A lightweight XML parser for NodeJS/JavaScript

Check out xmldoc on Github or just npm install xmldoc.

Ever need to parse a bit of XML in NodeJS? If so, you may be quite confused by your options. You might initially find an (excellent) callback-based parser, but that results in code like this:

Hm, I’m getting deja vu.

Of course, there are plenty of other libraries that let you deal with the whole document in memory at once. Libxmljs is solid, but requires bindings to libxml2 which means you have to compile it. I wanted a “pure JavaScript” module for simplicity and ease of deployment.

Node-elementtree is pure JS and looks pretty great, but I wanted a “one file” solution.

So, long story short, I wrote one and it’s a single JS file and it suits my needs perfectly. It uses the awesome pure-JS XML parser sax behind the scenes to build up an easily-traversable object hierarchy.

Behold:

You can use it in your Node.js app easily:

npm install xmldoc
…later…
var xmldoc = require('xmldoc');

Or just put it in a <script> tag and use it in the browser if you’d like. You can find examples for both cases in the repository.

As usual, you probably shouldn’t be loading large XML documents with this class if you are tight on memory. But if you’re just parsing little SOAP request snippets like I am, you’ll find it’s much easier to work with than stream-based parsers.

Go try it out and let me know what you think!

Notes (From Tumblr)

  1. nfarina posted this