Skip to content

Commit ee5d938

Browse files
committed
update tests
1 parent 6c931dc commit ee5d938

File tree

1 file changed

+41
-27
lines changed

1 file changed

+41
-27
lines changed

src/utils/xmlParser.ts

Lines changed: 41 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,51 @@
1-
export function parseXmlToJson(xml: string): any {
2-
const parser = new DOMParser();
3-
const doc = parser.parseFromString(xml, 'application/xml');
1+
import { ParsedApiConfiguration } from '../configuration/parsedApiConfigurationTypes';
2+
3+
type XmlJsonNode = { [key: string]: string | XmlJsonNode | XmlJsonNode[] };
4+
5+
function xmlNodeToJson(node: Element): XmlJsonNode | string {
6+
const obj: XmlJsonNode = {};
47

5-
const errorNode = doc.querySelector('parsererror');
6-
if (errorNode){throw new Error('Invalid XML');}
8+
for (const attr of Array.from(node.attributes)) {
9+
obj[attr.name] = attr.value;
10+
}
711

8-
function xmlNodeToJson(node: Element): any {
9-
const obj: any = {};
12+
for (const child of Array.from(node.children)) {
13+
const key = child.tagName;
14+
const childObj = xmlNodeToJson(child);
1015

11-
for (const attr of Array.from(node.attributes)) {
12-
obj[attr.name] = attr.value;
16+
if (typeof childObj === 'string') {
17+
// On ignore les strings dans les enfants structurés
18+
obj[key] = childObj;
19+
continue;
1320
}
1421

15-
for (const child of Array.from(node.children)) {
16-
const childObj = xmlNodeToJson(child);
17-
if (obj[child.tagName]) {
18-
if (!Array.isArray(obj[child.tagName])) {
19-
obj[child.tagName] = [obj[child.tagName]];
20-
}
21-
obj[child.tagName].push(childObj);
22-
} else {
23-
obj[child.tagName] = childObj;
22+
if (obj[key]) {
23+
if (!Array.isArray(obj[key])) {
24+
obj[key] = [obj[key] as XmlJsonNode];
2425
}
26+
(obj[key] as XmlJsonNode[]).push(childObj);
27+
} else {
28+
obj[key] = childObj;
2529
}
30+
}
2631

27-
const text = node.textContent?.trim();
28-
if (text && node.children.length === 0 && node.attributes.length === 0) {
29-
return text;
30-
}
31-
32-
return obj;
32+
const text = node.textContent?.trim();
33+
if (text && node.children.length === 0 && node.attributes.length === 0) {
34+
return text;
3335
}
3436

35-
const root = doc.documentElement;
36-
return { [root.tagName]: xmlNodeToJson(root) };
37-
}
37+
return obj;
38+
}
39+
40+
export function parseXmlToJson(xml: string): ParsedApiConfiguration {
41+
const parser = new DOMParser();
42+
const doc = parser.parseFromString(xml, 'application/xml');
43+
44+
const errorNode = doc.querySelector('parsererror');
45+
if (errorNode){ throw new Error('Invalid XML')};
46+
47+
const root = doc.documentElement;
48+
const result = { [root.tagName]: xmlNodeToJson(root) };
49+
50+
return result as unknown as ParsedApiConfiguration;
51+
}

0 commit comments

Comments
 (0)