Skip to content

Super small library to retrieve values and attributes from the XML AST generated by xml-reader

License

Notifications You must be signed in to change notification settings

eppsilon/xml-query

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

17 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

XML Query

Super small (~50 sloc) library to retrieve values and attributes from the XML AST generated by xml-reader.

Easy-to-use jQuery-like interface.

WORK IN PROGRESS!!!

Everything here is subject to change

Install

npm install --save xml-query

Usage

Reading xml streams/strings

// 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.

xmlQuery()

const xmlQuery = require('xml-query');

// creating from single ast
const xq = xmlQuery(ast);

// creating from an array of asts
const xq = xmlQuery([ast, ...more]);

.get()

Retrieve one of the elements.

xmlQuery(ast).find('body').get(2); // returns the `subject` node

.find()

Find by name. Including top level nodes and all its children.

xmlQuery(ast).find('body'); // returns a new xmlQuery object containing the body element

.attr()

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'

.children()

Returns a new xmlQuery object containing the children of the top level elements.

xmlQuery(ast).children();

.each()

Iterate over a xmlQuery object, executing a function for each element.

xmlQuery(ast).each(node => console.log(node.name));
// prints:
// from
// to
// subject
// body

.map()

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']

.prop()

Get the value of a property for the first element in the set.

xmlQuery(ast).prop('name'); // 'message'

.eq()

.first()

.last()

.length

.size()

About

Super small library to retrieve values and attributes from the XML AST generated by xml-reader

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • JavaScript 63.0%
  • TypeScript 37.0%