insomnia/packages/insomnia-xpath/index.js

46 lines
1.1 KiB
JavaScript
Raw Normal View History

const xpath = require('xpath');
2018-06-25 17:42:50 +00:00
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}>}
*/
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 = [];
// Functions return plain strings
if (typeof rawResults === 'string') {
results.push({
outer: rawResults,
inner: rawResults
});
} else {
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()
});
}
2017-09-22 13:48:47 +00:00
}
}
return results;
};