|
1 | 1 | import { ParsedApiConfiguration } from '../configuration/parsedApiConfigurationTypes';
|
2 | 2 |
|
3 |
| -type XmlJsonNode = { [key: string]: string | XmlJsonNode | XmlJsonNode[] }; |
| 3 | +type XmlJsonNode = { |
| 4 | + [key: string]: XmlJsonNode | XmlJsonNode[] | string; |
| 5 | + _: string; |
| 6 | +}; |
4 | 7 |
|
5 |
| -function xmlNodeToJson(node: Element): XmlJsonNode | string { |
6 |
| - const obj: XmlJsonNode = {}; |
7 |
| - |
8 |
| - for (const attr of Array.from(node.attributes)) { |
9 |
| - obj[attr.name] = attr.value; |
10 |
| - } |
11 |
| - |
12 |
| - for (const child of Array.from(node.children)) { |
13 |
| - const key = child.tagName; |
14 |
| - const childObj = xmlNodeToJson(child); |
15 |
| - |
16 |
| - if (typeof childObj === 'string') { |
17 |
| - // On ignore les strings dans les enfants structurés |
18 |
| - obj[key] = childObj; |
19 |
| - continue; |
20 |
| - } |
21 |
| - |
22 |
| - if (obj[key]) { |
23 |
| - if (!Array.isArray(obj[key])) { |
24 |
| - obj[key] = [obj[key] as XmlJsonNode]; |
25 |
| - } |
26 |
| - (obj[key] as XmlJsonNode[]).push(childObj); |
27 |
| - } else { |
28 |
| - obj[key] = childObj; |
| 8 | +function xmlNodeToJson(node: Element): XmlJsonNode { |
| 9 | + const obj: XmlJsonNode = { _: '' }; |
| 10 | + |
| 11 | + // Attributs |
| 12 | + for (const attr of Array.from(node.attributes)) { |
| 13 | + obj[attr.name] = attr.value; |
| 14 | + } |
| 15 | + |
| 16 | + // Enfants |
| 17 | + for (const child of Array.from(node.children)) { |
| 18 | + const tag = child.tagName; |
| 19 | + const childObj = xmlNodeToJson(child); |
| 20 | + if (obj[tag]) { |
| 21 | + if (!Array.isArray(obj[tag])) { |
| 22 | + obj[tag] = [obj[tag] as XmlJsonNode]; |
29 | 23 | }
|
| 24 | + (obj[tag] as XmlJsonNode[]).push(childObj); |
| 25 | + } else { |
| 26 | + obj[tag] = childObj; |
30 | 27 | }
|
31 |
| - |
32 |
| - const text = node.textContent?.trim(); |
33 |
| - if (text && node.children.length === 0 && node.attributes.length === 0) { |
34 |
| - return text; |
35 |
| - } |
36 |
| - |
37 |
| - return obj; |
38 | 28 | }
|
| 29 | + |
| 30 | + // Texte |
| 31 | + const text = node.textContent?.trim(); |
| 32 | + if (text && node.children.length === 0) { |
| 33 | + obj._ = text; |
| 34 | + } |
| 35 | + |
| 36 | + return obj; |
| 37 | +} |
| 38 | + |
39 | 39 |
|
40 | 40 | export function parseXmlToJson(xml: string): ParsedApiConfiguration {
|
41 | 41 | const parser = new DOMParser();
|
|
0 commit comments