Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save DOM as xml in a file with javascript

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>
like image 918
Giest Avatar asked Apr 03 '17 03:04

Giest


People also ask

Is the DOM an XML document?

The XML Document Object Model (DOM) class is an in-memory representation of an XML document. The DOM allows you to programmatically read, manipulate, and modify an XML document.

How do I save HTML file as XML?

Simply click the File button (the 3 lines), and click Save Page As. For example, I went to xml-sitemaps.com/sitemap.xml and clicked Save Page As. It saved as XML to my local machine and loaded as such. Without any HTML.


1 Answers

There's a very simple way to serialize your document to XML using XMLSerializer.

Here is the process:

  1. give an elment to XMLSerializer to serialize to XHTML (which is valid XML).
  2. optionally remove the xhtml namespace using String.prototype.replace
  3. use vkbeautify to pretty print (no native way to pretty print)

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>
like image 118
Rico Kahler Avatar answered Oct 20 '22 00:10

Rico Kahler