gaoluyang
2026-06-24 c0cb161bb52ce0fbdce5c66ec391d107c75e2452
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
51
function xmlStr2XmlObj(xmlStr) {
  // eslint-disable-next-line no-useless-assignment
  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 (obj[nodeName] === undefined) {
          obj[nodeName] = xml2json(item);
        } else {
          if (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 (error) {
    console.warn(error.message);
  }
}
 
function xmlObj2json(xml) {
  const xmlObj = xmlStr2XmlObj(xml);
  console.warn(xmlObj);
  let jsonObj = {};
  if (xmlObj.childNodes.length > 0) {
    jsonObj = xml2json(xmlObj);
  }
  return jsonObj;
}
 
export default xmlObj2json;