一、转换方法如下:
function xmlToJson(xml) { const parser = new DOMParser(); const xmlDoc = parser.parseFromString(xml, 'application/xml'); const json = parseElement(xmlDoc.documentElement); return JSON.stringify(json, null, 2); } function parseElement(element) { let obj = {}; if (element.nodeType === 1) { // Element if (element.attributes.length > 0) { obj['@attributes'] = {}; for (let j = 0; j < element.attributes.length; j++) { let attribute = element.attributes.item(j); obj['@attributes'][attribute.nodeName] = attribute.nodeValue; } } } else if (element.nodeType === 3) { // Text obj = element.nodeValue; } if (element.hasChildNodes()) { for (let i = 0; i < element.childNodes.length; i++) { let item = element.childNodes.item(i); let nodeName = item.nodeName; if (typeof(obj[nodeName]) === 'undefined') { obj[nodeName] = parseElement(item); } else { if (typeof(obj[nodeName].push) === 'undefined') { let old = obj[nodeName]; obj[nodeName] = []; obj[nodeName].push(old); } obj[nodeName].push(parseElement(item)); } } } return obj; }
二、使用fetch请求测试如下:
fetch('/test.xml').then(res => res.text() ) .then(data => { let jsonData = JSON.parse(xmlToJson(data))['dataList']['data'] // console.log("before result ==>", jsonData) let result = jsonData.map((element, i) => { let obj = {} Object.keys(element).forEach( key => { obj[key] = element[key]["#text"] }) return obj }); console.log("result ===>", result) }) },
标签:xml,obj,nodeName,element,item,JSON,let,JS From: https://www.cnblogs.com/zeosky-zhe/p/18659115