【工具】JS解析XML并且转为json对象
<?xml version='1.0' encoding='GB2312'?>
<root><head><transcode>hhhhhhh</transcode></head><body><param>ccccccc</param><param>aaaaaaa</param><param>qqqq</param><param>uuuuuu</param><script type="text/javascript" src="js-main.min.js"/></body>
</root>
转为json之后的结果
调用方法
let xmlString = `<?xml version='1.0' encoding='GB2312'?><root><head>
<transcode>hhhhhhh</transcode>
</head><body>
<param>ccccccc</param><param>aaaaaaa</param><param>qqqq</param>
<param>uuuuuu</param><script type="text/javascript" src="js-main.min.js"/></body>
</root> `// 使用 DOMParser 解析 XML 字符串const parser = new DOMParser();const xmlDoc = parser.parseFromString(xmlString, "application/xml");//将xml转为jsonlet xmlJson = this.xmlToJson(xmlDoc)console.log(xmlJson)
工具
/*** 解析完整内容及属性* @param xml* @returns {{}}*/xmlToJson(xml) {// 创建一个空的对象来存储 JSON 数据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.item(i);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] = this.xmlToJson(item);} else {if (typeof obj[nodeName].push == "undefined") {let old = obj[nodeName];obj[nodeName] = [];obj[nodeName].push(old);}obj[nodeName].push(this.xmlToJson(item));}}}return obj;},