2017-11-26 20:45:40 +00:00
|
|
|
const xpath = require('xpath');
|
2018-06-25 17:42:50 +00:00
|
|
|
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}>}
|
|
|
|
*/
|
2018-06-25 17:42:50 +00:00
|
|
|
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 = [];
|
2018-01-11 11:47:25 +00:00
|
|
|
|
|
|
|
// Functions return plain strings
|
|
|
|
if (typeof rawResults === 'string') {
|
|
|
|
results.push({
|
|
|
|
outer: rawResults,
|
2018-12-12 17:36:11 +00:00
|
|
|
inner: rawResults,
|
2018-01-11 11:47:25 +00:00
|
|
|
});
|
|
|
|
} else {
|
|
|
|
for (const result of rawResults || []) {
|
|
|
|
if (result.constructor.name === 'Attr') {
|
|
|
|
results.push({
|
|
|
|
outer: result.toString().trim(),
|
2018-12-12 17:36:11 +00:00
|
|
|
inner: result.nodeValue,
|
2018-01-11 11:47:25 +00:00
|
|
|
});
|
|
|
|
} else if (result.constructor.name === 'Element') {
|
|
|
|
results.push({
|
|
|
|
outer: result.toString().trim(),
|
2018-12-12 17:36:11 +00:00
|
|
|
inner: result.childNodes.toString(),
|
2018-01-11 11:47:25 +00:00
|
|
|
});
|
|
|
|
}
|
2017-09-22 13:48:47 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return results;
|
2017-11-26 20:45:40 +00:00
|
|
|
};
|