|
const xml2js = require("xml2js"); |
|
|
|
/** @type {Object<string, function>} */ |
|
const processors = { |
|
/** |
|
* Converts a string to snake_case |
|
* |
|
* @param {string} str - The string to convert |
|
* @returns {string} The snake_cased string |
|
*/ |
|
toSnakeCase: (str) => |
|
str |
|
.replace(/([A-Z])([A-Z])([a-z])/g, "$1_$2$3") // Handle end of acronym |
|
.replace(/([a-z])([A-Z])/g, "$1_$2") // Handle regular camelCase |
|
.toLowerCase(), |
|
|
|
/** |
|
* Parses numbers while preserving empty strings |
|
* |
|
* @param {string} str - The string to parse |
|
* @returns {number | string} Parsed number or original string if empty |
|
*/ |
|
parseNumbers: (str) => (str === "" ? str : xml2js.processors.parseNumbers(str)), |
|
}; |
|
|
|
/** |
|
* XML parser instance with custom processing options |
|
* |
|
* @type {xml2js.Parser} |
|
*/ |
|
const Parser = new xml2js.Parser({ |
|
tagNameProcessors: [xml2js.processors.stripPrefix, processors.toSnakeCase], |
|
attrNameProcessors: [xml2js.processors.stripPrefix, processors.toSnakeCase], |
|
valueProcessors: [processors.parseNumbers, xml2js.processors.parseBooleans], |
|
attrValueProcessors: [processors.parseNumbers, xml2js.processors.parseBooleans], |
|
explicitArray: false, // Don't create arrays for single elements |
|
ignoreAttrs: false, // Keep attributes |
|
mergeAttrs: true, // Merge attributes with element content |
|
normalize: true, // Trim whitespace |
|
explicitRoot: false, // Don't wrap in a root element |
|
}); |
|
|
|
/** |
|
* Asynchronously parses an XML string into a JavaScript object |
|
* |
|
* @example |
|
* const { parse } = pm.require("xml"); |
|
* |
|
* const xmlString = pm.response.text(); |
|
* const parsed = await parse(xmlString); //=> JS object |
|
* // ... do something with the parsed object |
|
* |
|
* @param {string} xmlString - The XML string to parse |
|
* @returns {Promise<Object>} A promise that resolves to the parsed object |
|
* @throws {Error} If parsing fails |
|
*/ |
|
const parse = async (xmlString) => Parser.parseStringPromise(xmlString); |
|
|
|
module.exports = { Parser, parse }; |