* Recursively converts a generic XML node back to a JavaScript value.
(tag: string, data: any)
| 54 | * Recursively converts a generic XML node back to a JavaScript value. |
| 55 | */ |
| 56 | function _fromGenericNode(tag: string, data: any): any { |
| 57 | if (tag === TAG_VALUE) { |
| 58 | // <value>123</value> without attributes is parsed as a primitive (number | string) |
| 59 | // whereas <value key="id">123</value> is parsed as an object with a "#text" field. |
| 60 | // Support both shapes. |
| 61 | if (_.isPlainObject(data)) { |
| 62 | return _.get(data, "#text", ""); |
| 63 | } |
| 64 | return data ?? ""; |
| 65 | } |
| 66 | |
| 67 | if (tag === TAG_ARRAY) { |
| 68 | const result: any[] = []; |
| 69 | _.forEach([TAG_VALUE, TAG_OBJECT, TAG_ARRAY], (childTag) => { |
| 70 | const childNodes = _.castArray(_.get(data, childTag, [])); |
| 71 | _.forEach(childNodes, (child) => { |
| 72 | result.push(_fromGenericNode(childTag, child)); |
| 73 | }); |
| 74 | }); |
| 75 | return result; |
| 76 | } |
| 77 | |
| 78 | // TAG_OBJECT |
| 79 | const obj: Record<string, any> = {}; |
| 80 | _.forEach([TAG_VALUE, TAG_OBJECT, TAG_ARRAY], (childTag) => { |
| 81 | const childNodes = _.castArray(_.get(data, childTag, [])); |
| 82 | _.forEach(childNodes, (child) => { |
| 83 | const key = _.get(child, "key", ""); |
| 84 | obj[key] = _fromGenericNode(childTag, child); |
| 85 | }); |
| 86 | }); |
| 87 | return obj; |
| 88 | } |
| 89 | |
| 90 | export function obj2xml<T>(obj: T): string { |
| 91 | const rootNode = _toGenericNode(obj)[TAG_OBJECT]; |