Languages
[Edit]
EN

JavaScript - parse XML data to POJO (to object)

4 points
Created by:
Cassia
1175

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]);

 

See also

  1. JavaScript - parse XML

Alternative titles

  1. JavaScript - convert XML data to POJO (to object)
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join