xml.ts 828 B

123456789101112131415161718192021222324252627
  1. import { XMLParser } from "fast-xml-parser"
  2. /**
  3. * Parses an XML string into a JavaScript object
  4. * @param xmlString The XML string to parse
  5. * @returns Parsed JavaScript object representation of the XML
  6. * @throws Error if the XML is invalid or parsing fails
  7. */
  8. export function parseXml(xmlString: string, stopNodes?: string[]): unknown {
  9. const _stopNodes = stopNodes ?? []
  10. try {
  11. const parser = new XMLParser({
  12. ignoreAttributes: false,
  13. attributeNamePrefix: "@_",
  14. parseAttributeValue: false,
  15. parseTagValue: false,
  16. trimValues: true,
  17. stopNodes: _stopNodes,
  18. })
  19. return parser.parse(xmlString)
  20. } catch (error) {
  21. // Enhance error message for better debugging
  22. const errorMessage = error instanceof Error ? error.message : "Unknown error"
  23. throw new Error(`Failed to parse XML: ${errorMessage}`)
  24. }
  25. }