读取xml文件,修改值/添加元素/属性并保存xml如何?
问题描述:
使用javascript,我想从磁盘读取xml文件,修改值/添加元素/属性并将xml保存回磁盘。读取xml文件,修改值/添加元素/属性并保存xml如何?
任何人都知道我能找到适用于IE和Firefox的例子吗?我已经找到了要阅读的例子,现在正在改变这个问题。
感谢
答
假设你正在试图读取并从浏览器写入到磁盘,而不是node.js的, 的第一步是使用file
类型的input
标签可以访问文件系统。
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
</head>
<body>
<input type="file" id="input" accept="text/xml">
<script src="script.js"></script>
</body>
只要选择了一个文件,我们想从元素中提取blob。 做这件事的好时机是在变化事件期间。
const input = document.querySelector('#input');
input.addEventListener('change',() => {
const file = input.files.item(0);
});
有多种方法可以将blob解析为元素树。 这里我利用浏览器分析HTTP请求中的xml文档这一事实。
function blobToDocument(blob, callback) {
const url = URL.createObjectURL(blob);
const request = new XMLHttpRequest();
request.open('Get', url);
request.responseType = 'document';
request.addEventListener('load',() => {
callback(request.response);
});
request.send();
}
blob被解析后,我们可以像操纵DOM树一样操纵它。
function editDocument(document) {
const element = document.createElement('editor');
element.textContent = 'JavaScript';
document.firstChild.appendChild(element);
return document;
}
为了将文件保存到磁盘,我们需要扭转解析, 的过程转换元件的树回字符串。
function documentToString(document) {
const serializer = new XMLSerializer();
return serializer.serializeToString(document);
}
剩下的唯一事情就是将文件发送回磁盘。 为了达到这个目的,我们可以在修改过的文件的链接上触发点击事件。
function download(string, mime) {
const blob = new Blob([string], { type: mime });
const a = document.createElement('a');
const url = URL.createObjectURL(blob);
a.href = url;
a.download = 'document.xml';
a.click();
}
下面是完整的代码
const input = document.querySelector('#input');
input.addEventListener('change',() => {
const file = input.files.item(0);
blobToDocument(file, (xmlDocument) => {
editDocument(xmlDocument);
download(documentToString(xmlDocument), "text/xml");
});
});
function blobToDocument(blob, callback) {
const url = URL.createObjectURL(blob);
const request = new XMLHttpRequest();
request.open('Get', url);
request.responseType = 'document';
request.addEventListener('load',() => {
callback(request.response);
});
request.send();
}
function editDocument(document) {
const element = document.createElement('editor');
element.textContent = 'JavaScript';
document.firstChild.appendChild(element);
return document;
}
function documentToString(document) {
const serializer = new XMLSerializer();
return serializer.serializeToString(document);
}
function download(string, mime) {
const blob = new Blob([string], { type: mime });
const a = document.createElement('a');
const url = URL.createObjectURL(blob);
a.href = url;
a.download = 'document.xml';
a.click();
}
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
</head>
<body>
<input type="file" id="input" accept="text/xml">
<script src="script.js"></script>
</body>