Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

109
Visualizações
How to write an XML file with certain format using JS?

I am trying to write an XML document from an HTML form using JavaScript with the following function:

JavaScript function:

function formToXml(form){
    var xmldata=['<?xml version="1.0" encoding="UTF-8"?>'];
    const elNames = ["author", "title"];
    xmldata.push("<book>");
    var inputs=form.elements;
    for(var i=0;i<inputs.length;i++){
        var el=document.createElement(elNames[i]);
        if (inputs[i].name){
            el.set("name",inputs[i].name);
            el.setAttribute("value",inputs[i].value);
            xmldata.push(el.outerHTML);
        }
    }
    xmldata.push("</book>");
    return xmldata.join("\n");
}

The file that is generated has the following format:

<?xml version="1.0" encoding="UTF-8"?>
<book>
   <author value="Something" name="author"/>
   <title value="Something" name="title"/>
</book>

I am trying to modify the method in order for the nodes to have the following format:

   <author>Something</author>
   <title>Something</title>

I know that setAttribute() doesn't work because it makes an attribute in the node. I can't find a function that sets the value like the example above.

Any suggestions?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can use the innerHTML attribute on the element to set the value.

function formToXml(form) {
  var xmldata = ['<?xml version="1.0" encoding="UTF-8"?>'];
  const elNames = ["author", "title"];
  xmldata.push("<book>");
  var inputs = form.elements;
  for (var i = 0; i < inputs.length; i++) {
    var el = document.createElement(elNames[i]);
    if (inputs[i].name) {
      el.innerHTML = inputs[i].value; // Set the innerHTML of the element
      xmldata.push(el.outerHTML);
    }
  }
  xmldata.push("</book>");
  return xmldata.join("\n");
}

Example output:

<?xml version="1.0" encoding="UTF-8"?>
<book>
  <author>Robert Louis Stevenson</author>
  <title>Treasure Island</title>
</book>
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda