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 = { } ;
4
7
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
+ }
7
11
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 ) ;
10
15
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 ;
13
20
}
14
21
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 ] ;
24
25
}
26
+ ( obj [ key ] as XmlJsonNode [ ] ) . push ( childObj ) ;
27
+ } else {
28
+ obj [ key ] = childObj ;
25
29
}
30
+ }
26
31
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 ;
33
35
}
34
36
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