在我的javascript中,我有以下内容:
let person = document.createElement('person');
let name = document.createElement('name');
let surname = document.createElement('surname');
person.appendChild(name);
person.appendChild(surname);
let xml = person;
如何保存我的" xml"文件中的变量(仅使用javascript)? OBS:内容不应该在一行中呈现,而是在树结构中:
<person>
<name></name>
<surname></surname>
</person>
答案 0 :(得分:4)
使用XMLSerializer
将文档序列化为XML的方法非常简单。
以下是流程:
xhtml
String.prototype.replace
命名空间
let person = document.createElement('person');
let name = document.createElement('name');
let surname = document.createElement('surname');
person.appendChild(name);
person.appendChild(surname);
// 1.) use XMLSerializer
let xml = new XMLSerializer().serializeToString(person);
// 2.) remove xml namespace
let xmlWithoutNamespace = xml.replace(' xmlns="http://www.w3.org/1999/xhtml"', '');
// 3.) use vkbeautify or your other favorite library to pretty print
console.log(vkbeautify.xml(xmlWithoutNamespace));
<script src="https://storage.googleapis.com/google-code-archive-downloads/v2/code.google.com/vkbeautify/vkbeautify.0.99.00.beta.js"></script>
答案 1 :(得分:1)
您可以使用.outerHTML
获取包含person
节点和子节点的字符串,data URI
表示文件,设置href
<a>
元素{ {1}}属性集。
download
您也可以创建代表let person = document.createElement('person');
let name = document.createElement('name');
let surname = document.createElement('surname');
person.appendChild(name);
person.appendChild(surname);
let xml = `data:application/xml,<?xml version="1.0" encoding="UTF-8"?>${encodeURIComponent(person.outerHTML)}`;
console.log(person, xml);
window.onload = () => {
let a = document.createElement("a");
let filename = "xmlfile.xml";
a.download = a.textContent = "xmlfile.xml";
a.href = xml;
document.body.appendChild(a);
}
数据的Blob
或File
个实例
XML
另见How to download a file without using <a> element with download attribute or a server?