Newer
Older
libxmljs-extra / src / find.js
@dreptin dreptin on 28 Apr 2021 721 bytes Initial commit
const utils = require('./utils.js');

/**
 * Finds the result of the provided XPath.
 * @param {Document} xmlDoc The instance of `Document` representating the XML document.
 * @param {string} xpath The XPath to get in `xmlDoc`.
 * @returns {(Element|Element[])} The found `Element` or `Element`s.
 */
function find(xmlDoc, xpath) {
  if (!xmlDoc) throw new Error('A Document must be provided.');
  if (typeof xpath !== 'string') throw new Error('path must be a string.');

  if (!xmlDoc.namespace) return xmlDoc.find(xpath);

  const fullXPath = utils.addNamespacePrefixInPath(xmlDoc.namespace.alias, xpath);

  return xmlDoc.find(fullXPath, { [xmlDoc.namespace.alias]: xmlDoc.namespace.url });
}

module.exports = find;