(string)
| 1 | function parseXML(string) { |
| 2 | /* |
| 3 | * Part 1 |
| 4 | * |
| 5 | * Parse the xml into a DOM-like json |
| 6 | * |
| 7 | * Input: <tag attribute="value">text node<inline>text node</inline>text node</tag> |
| 8 | * |
| 9 | * Output: |
| 10 | * { |
| 11 | * "name": "root", |
| 12 | * "children": [ |
| 13 | * { |
| 14 | * "name": "tag", |
| 15 | * "attrs": { |
| 16 | * "attribute": "value" |
| 17 | * }, |
| 18 | * "innerText": "text node text node", |
| 19 | * "children": [ |
| 20 | * { |
| 21 | * "name": "inline", |
| 22 | * "attrs": {}, |
| 23 | * "innerText": "text node", |
| 24 | * "children": [] |
| 25 | * } |
| 26 | * ] |
| 27 | * } |
| 28 | * ] |
| 29 | * } |
| 30 | * |
| 31 | */ |
| 32 | |
| 33 | const parser = new XMLParser(string); |
| 34 | |
| 35 | // Root of xml |
| 36 | const root = { |
| 37 | name: "root", |
| 38 | children: [], |
| 39 | }; |
| 40 | |
| 41 | // Store order for closing tags |
| 42 | const stack = [root]; |
| 43 | |
| 44 | // Create the new node and add it to the stack |
| 45 | parser.didStartElement = (name, attrs) => { |
| 46 | const node = { |
| 47 | name, |
| 48 | attrs, |
| 49 | innerText: "", |
| 50 | children: [], |
| 51 | }; |
| 52 | |
| 53 | stack.at(-1).children.push(node); |
| 54 | stack.push(node); |
| 55 | }; |
| 56 | |
| 57 | // Add the inner text to the node |
| 58 | parser.foundCharacters = (text) => { |
| 59 | const node = stack.at(-1); |
| 60 | node.innerText += node.innerText === "" ? text : " " + text; |
nothing calls this directly
no test coverage detected