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