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

/**
 * Counts the amount of results of the provided XPath.
 * @param {Document} xmlDoc The instance of `Document` representating the XML document.
 * @param {string} xpath The XPath to count in `xmlDoc`.
 * @returns {number} The amount of results.
 */
function count(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.get(`count(${xpath})`);

  const fullXPath = `count(${utils.addNamespacePrefixInPath(xmlDoc.namespace.alias, xpath)})`;

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

module.exports = count;