EN
JavaScript - parse XML data to POJO (to object)
4 points
In this short article, we would like to show how to parse XML data to JavaScript object (POJO).
Using this approach it is necessary to keep in mind that: letter case doesn't have metter.
xxxxxxxxxx
1
const parseXml = (xml) => {
2
const container = document.createElement('template');
3
container.innerHTML = xml;
4
return container.content;
5
}
6
7
const createObject = (xml) => {
8
const createObject = (document) => {
9
const children = document.children;
10
if (children.length > 0) {
11
const object = {};
12
for (let i = 0; i < children.length; ++i) {
13
const node = children[i];
14
const array = object[node.localName] || (object[node.localName] = []);
15
array.push(createObject(node));
16
}
17
return object;
18
} else {
19
return document.textContent;
20
}
21
};
22
return createObject(parseXml(xml));
23
};
24
25
26
// Usage example:
27
28
const xml = `
29
<User>
30
<ID>1</ID>
31
<Name>John</Name>
32
</User>
33
`;
34
35
const object = createObject(xml);
36
37
console.log(object.user[0].id[0]);
38
console.log(object.user[0].name[0]);
Using this approach it is necessary to keep in mind that: letter case has metter.
xxxxxxxxxx
1
const parseXml = (xml) => {
2
const parser = new DOMParser();
3
return parser.parseFromString(xml, 'text/xml');
4
}
5
6
const createObject = (xml) => {
7
const createObject = (document) => {
8
const children = document.children;
9
if (children.length > 0) {
10
const object = {};
11
for (let i = 0; i < children.length; ++i) {
12
const node = children[i];
13
const array = object[node.tagName] || (object[node.tagName] = []);
14
array.push(createObject(node));
15
}
16
return object;
17
} else {
18
return document.textContent;
19
}
20
};
21
return createObject(parseXml(xml));
22
};
23
24
25
// Usage example:
26
27
const xml = `
28
<User>
29
<ID>1</ID>
30
<Name>John</Name>
31
</User>
32
`;
33
34
const object = createObject(xml);
35
36
console.log(object.User[0].ID[0]);
37
console.log(object.User[0].Name[0]);