insomnia/packages/insomnia-xpath/index.js

37 lines
882 B
JavaScript
Raw Normal View History

const xpath = require('xpath');
const {DOMParser} = require('xmldom');
2017-09-22 13:48:47 +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;
};