xml2json.js
1.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
function xmlStr2XmlObj(xmlStr) {
let xmlObj = {};
if (document.all) {
const xmlDom = new window.ActiveXObject("Microsoft.XMLDOM");
xmlDom.loadXML(xmlStr);
xmlObj = xmlDom;
} else {
xmlObj = new DOMParser().parseFromString(xmlStr, "text/xml");
}
return xmlObj;
}
function xml2json(xml) {
try {
let obj = {};
if (xml.children.length > 0) {
for (let i = 0; i < xml.children.length; i++) {
const item = xml.children.item(i);
const nodeName = item.nodeName;
if (typeof obj[nodeName] == "undefined") {
obj[nodeName] = xml2json(item);
} else {
if (typeof obj[nodeName].push == "undefined") {
const old = obj[nodeName];
obj[nodeName] = [];
obj[nodeName].push(old);
}
obj[nodeName].push(xml2json(item));
}
}
} else {
obj = xml.textContent;
}
return obj;
} catch (e) {
console.log(e.message);
}
}
function xmlObj2json(xml) {
const xmlObj = xmlStr2XmlObj(xml);
console.log(xmlObj);
let jsonObj = {};
if (xmlObj.childNodes.length > 0) {
jsonObj = xml2json(xmlObj);
}
return jsonObj;
}
export default xmlObj2json;