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).
Practical examples
Example 1:
Using this approach it is necessary to keep in mind that: letter case doesn't have metter.
// ONLINE-RUNNER:browser;
const parseXml = (xml) => {
const container = document.createElement('template');
container.innerHTML = xml;
return container.content;
}
const createObject = (xml) => {
const createObject = (document) => {
const children = document.children;
if (children.length > 0) {
const object = {};
for (let i = 0; i < children.length; ++i) {
const node = children[i];
const array = object[node.localName] || (object[node.localName] = []);
array.push(createObject(node));
}
return object;
} else {
return document.textContent;
}
};
return createObject(parseXml(xml));
};
// Usage example:
const xml = `
<User>
<ID>1</ID>
<Name>John</Name>
</User>
`;
const object = createObject(xml);
console.log(object.user[0].id[0]);
console.log(object.user[0].name[0]);
Example 2:
Using this approach it is necessary to keep in mind that: letter case has metter.
// ONLINE-RUNNER:browser;
const parseXml = (xml) => {
const parser = new DOMParser();
return parser.parseFromString(xml, 'text/xml');
}
const createObject = (xml) => {
const createObject = (document) => {
const children = document.children;
if (children.length > 0) {
const object = {};
for (let i = 0; i < children.length; ++i) {
const node = children[i];
const array = object[node.tagName] || (object[node.tagName] = []);
array.push(createObject(node));
}
return object;
} else {
return document.textContent;
}
};
return createObject(parseXml(xml));
};
// Usage example:
const xml = `
<User>
<ID>1</ID>
<Name>John</Name>
</User>
`;
const object = createObject(xml);
console.log(object.User[0].ID[0]);
console.log(object.User[0].Name[0]);