@yuhere/js-simple-xml
v1.0.2
Published
Parse XML into plain JavaScript objects with a simple API.
Readme
js-simple-xml
A simple XML parser for JavaScript. Works in both Node.js and browser environments.
Installation
npm install @yuhere/js-simple-xmlUsage
Basic parsing
import { simplify } from '@yuhere/js-simple-xml';
const xml = `<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>`;
const result = simplify(xml);
// { to: 'Tove', from: 'Jani', heading: 'Reminder', body: "Don't forget me this weekend!" }Auto-array for duplicate elements
When multiple sibling elements share the same tag name, their values are automatically collected into an array:
const xml = `<note>
<to>Tove</to>
<heading>Reminder</heading>
<from>Jani</from>
<heading>Reminder 2</heading>
</note>`;
const result = simplify(xml);
// { to: 'Tove', from: 'Jani', heading: ['Reminder', 'Reminder 2'] }Force array
Use forceArray to ensure specific elements are always arrays, even when only one exists. Entries can be node names, dot-separated xpaths, or glob patterns:
const xml = `<note><to>Tove</to><from>Jani</from></note>`;
const result = simplify(xml, { forceArray: ['to', 'note.from'] });
// { to: ['Tove'], from: ['Jani'] }
// Glob pattern support:
const result2 = simplify(xml, { forceArray: ['*.to'] });
// { to: ['Tove'], from: 'Jani' }Transform
Provide a transform callback to reshape values during simplification. It receives the xpath, the raw XmlElement, and the simplified value:
const xml = `<note><count>5</count></note>`;
const result = simplify(xml, {
transform: (xpath, node, value) => {
if (xpath === 'note.count') return Number(value);
return value;
}
});
// { count: 5 }Force array with callback
You can also pass a callback function to forceArray for dynamic matching. It receives the xpath and the element node, and should return true to force that element to an array:
const xml = `<note><to>Tove</to><from>Jani</from></note>`;
const result = simplify(xml, {
forceArray: (xpath, node) => xpath === 'note.to' || node.name === 'from'
});
// { to: ['Tove'], from: ['Jani'] }API
simplify(xml: string, options?: SimplifyOptions): SimplifiedXml
Parses an XML string into a plain JavaScript object.
| Option | Type | Description |
|---|---|---|
| forceArray | string[] \| (xpath, node) => boolean | Element names, xpaths ("parent.child"), globs ("*.name"), or a callback to always treat as arrays |
| transform | (xpath, node, value) => SimplifiedXml | Callback invoked on every element during simplification |
License
MIT — see LICENSE for details.
