// 树形展示
<el-tree :data="treeData" default-expand-all>
<div slot-scope="{ data }" class="custom-tree-node">
<span>{{ data.label }}</span><span v-if="data.text">: {{data.text}}</span>
</div>
</el-tree>
// 加载xml字符串
parseXml(xmlStr) {
const xmlDoc = this.loadXmlStr(xmlStr);
this.treeData = this.getTreeData(xmlDoc);
},
loadXmlStr(xmlStr) {
var xmlDoc = null;
if (window.DOMParser) {
// 非IE浏览器
xmlDoc = (new DOMParser()).parseFromString(xmlStr, "text/xml");
} else {
// IE浏览器
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
// 或者:xmlDoc = new ActiveXObject("MSXML2.DOMDocument");
xmlDoc.async = "false"; // 不启用异步,保证加载文件成功之前不会进行下面操作
xmlDoc.loadXML(xmlStr);
}
return xmlDoc;
},
getTreeData(node) {
let children = []
for (let i = 0; i < node.childNodes.length; i++) {
const childNode = node.childNodes[i]
if (childNode.nodeType === Node.ELEMENT_NODE) {
let vl = childNode.innerHTML;
children.push({
label: childNode.nodeName,
attribute: this.getAttributeData(childNode),
text: vl.indexOf('>') != -1 ? '' : vl,
children: this.getTreeData(childNode)
})
}
}
return children
},
getAttributeData(node) {
const attributeData = []
for (let i = 0; i < node.attributes.length; i++) {
const attributeNode = node.attributes[i]
attributeData.push({
name: attributeNode.name,
value: attributeNode.value
})
}
return attributeData
},
// 导出
exportXml(str, fileName) {
// let str = '<?xml version="1.0" encoding="utf-8" ?>\n<dataSource>\n';
// dataList.forEach(dataItem => {
// str += `<dataItem>\n`;
// columns.forEach(columnsItem => {
// str += `<${columnsItem.key}>${dataItem[columnsItem.key]}</${columnsItem.key}>\n`;
// });
// str += `</dataItem>\n`;
// });
// str += '</dataSource>';
let downloadLink = document.createElement('a');
let uri = window.URL.createObjectURL(new Blob([str], { type: 'text/plain;charset=utf-8,\ufeff' }));
downloadLink.href = uri;
downloadLink.download = `${fileName}.txt`;
downloadLink.click();
window.URL.revokeObjectURL(uri);
}