Home » Javascript » Fill form with xml file selected by user

Fill form with xml file selected by user

Posted by: admin August 19, 2018 Leave a comment


Part of the html form

<div id="form1">

        <input class="a" type="date" name="Data" id="Data" placeholder="Data" />
        <input class="a" type="time" name="Hora" id="Hora" placeholder="Hora" />
        <input class="a" type="text" name="Sala" id="Sala" placeholder="Sala" />
        <input class="a" type="text" name="Edifício" id="Edifício" placeholder="Edifício" />
        <input class="a" type="text" name="Cidade" id="Cidade" placeholder="Cidade" />
        <input class="a" type="text" name="País" id="País" placeholder="País" />

I have a html form, and its capable of creating a XML file with the inputs value like this. The “key” tag is the name of the input, and the “value” tag is the value.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<AssetInfo xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>
<name>transferir (1).jpeg</name>
     <value>sala 2</value>

And I want to fill the form inputs with the values inside the “value” tag.

I tried to do this, the user select the xml file, it searchs the xml file for the “key” and value “tag” store the text insert in those tags, then search in all the inputs of the form the “name” = text in the “key” tag and fill with the value from the “value” tag.

function loadData(fileInput) {
    "use strict";
  var file = fileInput.files[0];
  var fileURL = URL.createObjectURL(file);
  var req = new XMLHttpRequest();
  req.open('GET', fileURL);
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(fileURL, 'text/xml');   

  req.onload = function() { 
   populateData(fileInput.form, xmlDoc);

  req.onerror = function() {
    console.log('Error loading XML file.');

function populateData(form, xmlDoc){ 
    "use strict";
  var root = xmlDoc.documentElement;
  var metadataNodes =root.querySelectorAll("customMetaDados");
    var map={};
    metadataNodes.forEach(function(metadata) {
    var key = metadata.querySelector('key').textContent;
    var value = metadata.querySelector('value').textContent;
    map[key] = value;

    for (var i = 0; i < form.elements.length; i++) {
    var input = form.elements[i];
        input.value = map[input.name] || '';        

function readXML(){
    "use strict";
    var xml = new XMLHttpRequest();
    xml.open('GET', 'xml/*', false);
    var xmlData=xml.responseXML;
        xmlData=(new DOMParser()).parseFromString(xml.responseText,'text/xml');
        var emp = xml.Data.getElementByTagName("customMetaDados");

        for(var i=0;i<emp.length;i++){
            var value= emp[i].getElementsByTagNAme("value")[i].firstCHild.data;