https://blog.csdn.net/cuozhun3051/article/details/107061372
xml文件先转成xml对象,再由xml对象转为JSON
// 10.10.0.99:8000/api/file/getFile//test/2011.xml
// 传路径
let LoadXMLFile = xmlFile => {
let xmlDom = null;
if (window.ActiveXObject) {
xmlDom = new ActiveXObject("Microsoft.XMLDOM");
//xmlDom.loadXML(xmlFile);//如果用的是XML字符串
xmlDom.load(xmlFile); //如果用的是xml文件。
} else if (document.implementation && document.implementation.createDocument) {
let xmlhttp = new window.XMLHttpRequest();
xmlhttp.open("GET", xmlFile, false);
xmlhttp.send(null);
xmlDom = xmlhttp.responseXML.documentElement;//一定要有根节点(否则google浏览器读取不了)
} else {
xmlDom = null;
}
return xmlDom;
}
let xmlToJson = xml => {
// Create the return object
let obj = {};
// element
if (xml.nodeType == 1) {
// do attributes
if (xml.attributes.length > 0) {
obj["@attributes"] = {};
for (var j = 0; j < xml.attributes.length; j++) {
var attribute = xml.attributes.item(j);
obj["@attributes"][attribute.nodeName] = attribute.nodeValue;
}
}
// text
} else if (xml.nodeType == 3) {
obj = xml.nodeValue;
}
// do children
if (xml.hasChildNodes()) {
for (var i = 0; i < xml.childNodes.length; i++) {
var item = xml.childNodes.item(i);
var nodeName = item.nodeName;
if (typeof (obj[nodeName]) == "undefined") {
obj[nodeName] = xmlToJson(item);
} else {
if (typeof (obj[nodeName].push) == "undefined") {
var old = obj[nodeName];
obj[nodeName] = [];
obj[nodeName].push(old);
}
obj[nodeName].push(xmlToJson(item));
}
}
}
return obj;
}
export {LoadXMLFile,xmlToJson}
网友评论