|
发表于 2023-4-14 20:29:23
|
显示全部楼层
江苏省苏州市
以下是在JavaScript中将JSON和XML相互转换的示例代码:
// 将JSON转换为XMLfunction jsonToXml(json) { let xml = ''; for (let prop in json) { xml += `<${prop}>`; if (typeof json[prop] === 'object') { xml += jsonToXml(new Object(json[prop])); } else { xml += json[prop]; } xml += `</${prop}>`; } return xml;}// 将XML转换为JSONfunction xmlToJson(xml) { let obj = {}; if (xml.nodeType === 1) { if (xml.attributes.length > 0) { obj['@attributes'] = {}; for (let i = 0; i < xml.attributes.length; i++) { let attribute = xml.attributes; obj['@attributes'][attribute.nodeName] = attribute.nodeValue; } } } else if (xml.nodeType === 3) { obj = xml.nodeValue; } if (xml.hasChildNodes()) { for (let i = 0; i < xml.childNodes.length; i++) { let item = xml.childNodes.item(i); let nodeName = item.nodeName; if (typeof obj[nodeName] === 'undefined') { obj[nodeName] = xmlToJson(item); } else { if (typeof obj[nodeName].push === 'undefined') { let old = obj[nodeName]; obj[nodeName] = []; obj[nodeName].push(old); } obj[nodeName].push(xmlToJson(item)); } } } return obj;}
|
|