以下是一个可以在 Vue 中读取本地 XML 文件并使用 JavaScript 内置的解析器解析 XML 的示例代码:
<template>
<div>
<input type="file" @change="onFileChange">
<el-tree :data="treeData" @node-click="handleNodeClick"></el-tree>
<el-table :data="tableData" v-show="showTable">
<el-table-column prop="name" label="属性名"></el-table-column>
<el-table-column prop="value" label="属性值"></el-table-column>
</el-table>
</div>
</template>
<script>
export default {
data() {
return {
xmlData: null,
treeData: [],
tableData: [],
showTable: false
}
},
methods: {
onFileChange(e) {
const file = e.target.files[0]
const reader = new FileReader()
reader.onload = (e) => {
this.xmlData = e.target.result
this.parseXml()
}
reader.readAsText(file)
},
parseXml() {
const parser = new DOMParser()
const xmlDoc = parser.parseFromString(this.xmlData, "text/xml")
const rootNode = xmlDoc.documentElement
this.treeData = this.getTreeData(rootNode)
},
getTreeData(node) {
let children = []
for (let i = 0; i < node.childNodes.length; i++) {
const childNode = node.childNodes[i]
if (childNode.nodeType === Node.ELEMENT_NODE) {
children.push({
label: childNode.nodeName,
attribute: this.getAttributeData(childNode),
text: childNode.textContent.trim(),
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
},
handleNodeClick(data) {
if (data.attribute.length > 0 || data.text) {
this.showTable = true
this.tableData = [...data.attribute, { name: 'text', value: data.text }]
} else {
this.showTable = false
}
}
}
}
</script>
这个示例代码中,我们使用了 input
标签来选择本地 XML 文件,在 onFileChange
方法中使用 FileReader 将文件内容读取为字符串,然后使用 DOMParser 对解析出来的字符串进行解析得到一个 XML 的文档对象。接着,我们使用递归方式将 XML 文档对象转换为树结构,最后使用 el-tree 来表示整个 XML 结构。当用户点击某个节点时,我们会检查该节点是否有属性或者文本内容,如果有的话就将它们显示在 el-table 上面。