Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

154
Views
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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!