README
XLAX
Simple XML extraction via xpath
Use this when you need to loosen XML up and get it flowing. This is basically a wrapper for the excellent xpath npm module.
Use xpath to extract the content you're looking for. It comes with sane defaults and utility methods, for example, defaulting to extracting the text content of the nodes, and a method for getting the first result.
Note: This module loosens things up - it does not throw errors for invalid xpaths. Instead, it will return an empty string for extractOne()
and an empty array for extract()
. The goal of this module is to help you write resilient code that can ingest 3rd party xml (that is open to unexpected changes) and parse the pieces you need.
Examples:
xlax.extractOne(path)
Extract the first result from your xpath expression. Now you don't have to worry about returning an array of results when you're expecting a string.
var xlax = require('xlax');
var music = new xlax('<music><artists><artist><name>TallyHall</name><yearFormed>2002</yearFormed></artist><artist><name>BenFoldsFive</name><yearFormed>1993</yearFormed></artist><artist><name>Wilco</name><yearFormed>1994</yearFormed></artist></artists></music>');
console.log(music.extractOne('//music/artists/artist/name/text()')); // Tally Hall
xlax.extract(path)
Return an array of instances of xlax for each match, so that you can extract the data from each result.
var xlax = require('xlax');
var music = new xlax('<music><artists><artist><name>Tally Hall</name><yearFormed>2002</yearFormed></artist><artist><name>Ben Folds Five</name><yearFormed>1993</yearFormed></artist><artist><name>Wilco</name><yearFormed>1994</yearFormed></artist></artists></music>');
var artists = music.extract('//music/artists/artist');
for (var i = 0; i < artists.length; i++) {
console.log(artists[i].extractOne('/artist/name/text()')); // each result
console.log(artists[i].extractOne('/artist/yearFormed/text()')); // each result
};
xlax.forEach(path)
Iterate over each instance of xlax for each match, so that you can extract the data from each result.
var xlax = require('xlax');
var music = new xlax('<music><artists><artist><name>Tally Hall</name><yearFormed>2002</yearFormed></artist><artist><name>Ben Folds Five</name><yearFormed>1993</yearFormed></artist><artist><name>Wilco</name><yearFormed>1994</yearFormed></artist></artists></music>');
music.forEach('//music/artists/artist', function(node) { // grab each artist
console.log(node.toString()); // <artist><name>...
console.log(node.extractOne('/artist/name/text()')); // TallyHall, then Ben Folds Five, etc.
console.log(node.extractOne('/artist/yearFormed/text()')); // 2002, then 1993, etc.
});
Utility methods
xlax.toString()
Returns either the xml data passed into the object or the instance XML if called on the object(s) returned by xlax.extract().
Utility properties
xlax.length
Returns the length of the matched path passed into xlax.extract().