import { Parser } from '.' import { Token } from '../token' export const createObject = (startTag: Token.StartTag) => { const object: any = {} startTag.atts && startTag.atts.forEach(att => { object[att.name.toString()] = att.value.toString() }) return object } /** * Simplified, opiniated, representation of an xml element * * Produce an object where attributes are properties (string) of the object and * children element are arrays of objects. * * @remarks * - Fully qualified names are used for property names. * - All texts are collected in property `#text` */ export class XmlToObjectParser implements Parser.IParser { onStart(startTag: Token.StartTag, parentCtx: any) { const object = createObject(startTag) const tagName = startTag.tagName const collection: any[] = parentCtx[tagName] || (parentCtx[tagName] = []) collection.push(object) } onText(text: Token.Text | Token.CDATA, ctx: any) { ctx['#text'] = ctx['#text'] ? ctx['#text'] + text.textContent : text.textContent } onChild() { return this } }