2017-11-26 20:45:40 +00:00
|
|
|
const xpath = require('xpath');
|
|
|
|
const {DOMParser} = require('xmldom');
|
2017-09-22 13:48:47 +00:00
|
|
|
|
2017-11-26 20:45:40 +00:00
|
|
|
/**
|
|
|
|
* Query an XML blob with XPath
|
|
|
|
* @param xml {string}
|
|
|
|
* @param query {string}
|
|
|
|
* @returns {Array<{outer: string, inner: string}>}
|
|
|
|
*/
|
|
|
|
module.exports.query = function (xml, query) {
|
2017-09-22 13:48:47 +00:00
|
|
|
const dom = new DOMParser().parseFromString(xml);
|
|
|
|
let rawResults = [];
|
|
|
|
|
|
|
|
try {
|
|
|
|
rawResults = xpath.select(query, dom);
|
|
|
|
} catch (err) {
|
|
|
|
throw new Error(`Invalid XPath query: ${query}`);
|
|
|
|
}
|
|
|
|
|
|
|
|
const results = [];
|
|
|
|
for (const result of rawResults || []) {
|
|
|
|
if (result.constructor.name === 'Attr') {
|
|
|
|
results.push({
|
|
|
|
outer: result.toString().trim(),
|
|
|
|
inner: result.nodeValue
|
|
|
|
});
|
|
|
|
} else if (result.constructor.name === 'Element') {
|
|
|
|
results.push({
|
|
|
|
outer: result.toString().trim(),
|
|
|
|
inner: result.childNodes.toString()
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return results;
|
2017-11-26 20:45:40 +00:00
|
|
|
};
|