Reputation: 495
In my javascript I have the following:
let person = document.createElement('person');
let name = document.createElement('name');
let surname = document.createElement('surname');
person.appendChild(name);
person.appendChild(surname);
let xml = person;
How do I save my "xml" variable in a file (using javascript only)? OBS: The content should not be presented in a single line, but in the tree structure:
<person>
<name></name>
<surname></surname>
</person>
Upvotes: 5
Views: 5692
Reputation: 1
You can use .outerHTML
to get string containing person
node and child nodes, data URI
representation of file, set a href
of <a>
element with download
attribute set.
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);
}
You can alternatively create a Blob
or File
instance representing XML
data
let person = document.createElement('person');
let name = document.createElement('name');
let surname = document.createElement('surname');
person.appendChild(name);
person.appendChild(surname);
let xml = `<?xml version="1.0" encoding="UTF-8"?>${person.outerHTML}`;
let file = new File([xml]
, "xmlfile.xml", {type:"application/xml"});
console.log(person, xml, file);
let url;
window.onload = () => {
let a = document.createElement("a");
let filename = "xmlfile.xml";
a.download = a.textContent = "xmlfile.xml";
url = URL.createObjectURL(file);
a.href = url;
document.body.appendChild(a);
a.onclick = () => {
window.onfocus = () => {
window.onfocus = null;
URL.revokeObjectURL(url);
if ("close" in file && !file.isClosed) file.close();
}
}
}
See also How to download a file without using <a> element with download attribute or a server?
Upvotes: 1
Reputation: 19202
There's a very simple way to serialize your document to XML using XMLSerializer
.
Here is the process:
xhtml
namespace using 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>
Upvotes: 5