Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add XML declaration to XML document programmatically

I want to add the declaration to an XML document generated in Javascript, but I did not find sufficient documentation.

Let's say I want to create programmatically (using Javascript) the following XML document:

<?xml version="1.0" encoding="UTF-8"?>
<people>
  <person first-name="eric" last-name="jung" />
</people>

Here is the code that I did:

let doc = document.implementation.createDocument("", "", null);
let peopleElem = doc.createElement("people");

let personElem = doc.createElement("person");
personElem.setAttribute("first-name", "eric");
personElem.setAttribute("last-name", "jung");

peopleElem.appendChild(personElem);
doc.appendChild(peopleElem);

let docStr = new XMLSerializer().serializeToString(doc.documentElement);
console.log(docStr);

// produces:
// <people>
//   <person first-name="eric" last-name="jung" />
// </people>

// and not:
// <?xml version="1.0" encoding="UTF-8"?>
// <people>
//   <person first-name="eric" last-name="jung" />
// </people>

How should I do to get the <?xml version="1.0" encoding="UTF-8"?> in the generated XML?

Note: I know that adding a declaration is useless in this case, but eventually I want to use a specific namespace and also add custom XML entities to my document.

Thank you for your help.

like image 572
JacopoStanchi Avatar asked Sep 05 '25 16:09

JacopoStanchi


1 Answers

Here is one way to do it.

See the list of compatible node types for XMLSerializer.

There is ProcessingInstruction node that can be created with createProcessingInstruction method.

Finally, you need to serialize the whole document, not only the documentElement.

const doc = document.implementation.createDocument("", "", null);
const peopleElem = doc.createElement("people");

const pi = doc.createProcessingInstruction('xml', 'version="1.0" encoding="UTF-8"');
doc.insertBefore(pi, doc.firstChild);

const personElem = doc.createElement("person");

personElem.setAttribute("first-name", "eric");
personElem.setAttribute("last-name", "jung");

peopleElem.appendChild(personElem);

doc.appendChild(peopleElem);

const docStr = new XMLSerializer().serializeToString(doc);

console.log(docStr);
like image 55
Ernesto Stifano Avatar answered Sep 07 '25 08:09

Ernesto Stifano