File tree Expand file tree Collapse file tree 1 file changed +13
-8
lines changed Expand file tree Collapse file tree 1 file changed +13
-8
lines changed Original file line number Diff line number Diff line change
1
+ // src/utils/xmlParser.ts
1
2
export function parseXmlToJson ( xml : string ) : unknown {
2
3
const parser = new DOMParser ( ) ;
3
4
const doc = parser . parseFromString ( xml , 'application/xml' ) ;
4
5
5
6
const errorNode = doc . querySelector ( 'parsererror' ) ;
6
7
if ( errorNode ) {
7
- throw new Error ( 'Invalid XML' ) ;
8
- }
8
+ throw new Error ( 'Invalid XML' ) ; }
9
9
10
10
function xmlNodeToJson ( node : Element ) : unknown {
11
11
const obj : Record < string , unknown > = { } ;
12
12
13
+ // Attributs
13
14
for ( const attr of Array . from ( node . attributes ) ) {
14
15
obj [ attr . name ] = attr . value ;
15
16
}
16
17
18
+ // Enfants
17
19
for ( const child of Array . from ( node . children ) ) {
18
20
const childObj = xmlNodeToJson ( child ) ;
19
- if ( obj [ child . tagName ] ) {
20
- if ( ! Array . isArray ( obj [ child . tagName ] ) ) {
21
- obj [ child . tagName ] = [ obj [ child . tagName ] ] ;
21
+ const key = child . tagName ;
22
+ const existing = obj [ key ] ;
23
+
24
+ if ( existing !== undefined ) {
25
+ if ( Array . isArray ( existing ) ) {
26
+ existing . push ( childObj ) ;
27
+ } else {
28
+ obj [ key ] = [ existing , childObj ] ;
22
29
}
23
- ( obj [ child . tagName ] as unknown [ ] ) . push ( childObj ) ;
24
-
25
30
} else {
26
- obj [ child . tagName ] = childObj ;
31
+ obj [ key ] = childObj ;
27
32
}
28
33
}
29
34
You can’t perform that action at this time.
0 commit comments