EN
JavaScript - parse XML in web browser
3 points
In this article, we would like to show you how to parse XML using web browser JavaScript.
xxxxxxxxxx
1
const parseXml = (xml) => {
2
const parser = new DOMParser();
3
return parser.parseFromString(xml, 'text/xml');
4
};
5
6
7
// Usage example:
8
9
const xml = `
10
<user>
11
<id>1</id>
12
<name>John</name>
13
</user>
14
`;
15
16
const instance = parseXml(xml);
17
18
const userElement = instance.children[0];
19
const idElement = userElement.children[0];
20
const nameElement = userElement.children[1];
21
22
console.log(idElement.textContent); // 1
23
console.log(nameElement.textContent); // John
xxxxxxxxxx
1
const parseXml = (xml) => {
2
const container = document.createElement('template');
3
container.innerHTML = xml;
4
return container.content;
5
};
6
7
8
// Usage example:
9
10
const xml = `
11
<user>
12
<id>1</id>
13
<name>John</name>
14
</user>
15
`;
16
17
const instance = parseXml(xml);
18
19
const userElement = instance.children[0];
20
const idElement = userElement.children[0];
21
const nameElement = userElement.children[1];
22
23
console.log(idElement.textContent); // 1
24
console.log(nameElement.textContent); // John