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.