Super small (~50 sloc) library to retrieve values and attributes from the XML AST generated by xml-reader.
Easy-to-use jQuery-like interface.
Everything here is subject to change
npm install --save xml-query
// given this xml
const xml =
`<message id="1001" date="2016-06-19">
<from>Bob</from>
<to>Alice</to>
<subject>Hello</subject>
<body>Lorem ipsum dolor sit amet, consectetur adipiscing elit</body>
</message>`;
// we can use the xml-reader module to get the ast from the xml source
const reader = xmlReader.create(); // see https://www.npmjs.com/package/xml-reader
reader.on('done', ast => {
// do something with the ast
});
reader.parse(xml);
Following examples will use this ast.
const xmlQuery = require('xml-query');
// creating from single ast
const xq = xmlQuery(ast);
// creating from an array of asts
const xq = xmlQuery([ast, ...more]);
Retrieve one of the elements.
xmlQuery(ast).find('body').get(2); // returns the `subject` node
Find by name. Including top level nodes and all its children.
xmlQuery(ast).find('body'); // returns a new xmlQuery object containing the body element
Get all attributes. If a name is provided, it returns the value for that key.
xmlQuery(ast).attr(); // {id: '1001', date: '2016-06-19'}
xmlQuery(ast).attr('id'); // '1001'
Returns a new xmlQuery object containing the children of the top level elements.
xmlQuery(ast).children();
Iterate over a xmlQuery object, executing a function for each element.
xmlQuery(ast).each(node => console.log(node.name));
// prints:
// from
// to
// subject
// body
Iterate over a xmlQuery object, executing a function for each element. Returns the results in an array.
xmlQuery(ast).map(node => node.name); // ['from', 'to', 'subject', 'body']
Get the value of a property for the first element in the set.
xmlQuery(ast).prop('name'); // 'message'