Home » Javascript » Trying to populate form with XML file inserted by user with FileReader API

Trying to populate form with XML file inserted by user with FileReader API

Posted by: admin August 19, 2018 Leave a comment


Doens’t show any error but it doesn’t populate the form either and i don’t know what’s wrong

Html input

<label><input type="file" style="display: none;" id="fileChooser">Ler XML</label>  

JS file

  var fileChooser = document.getElementById('fileChooser');

function parseTextAsXml(text) {
    "use strict";
    var parser = new DOMParser(),
        xmlDom = parser.parseFromString(text, "text/xml");
After parsing called the function "populateData" with the parsed element and the form

    populateData(document.getElementById("xmlForm"), xmlDom);

function waitForTextReadComplete(reader) {
    "use strict";
    reader.onloadend = function(event) {
        var text = event.target.result;

function handleFileSelection() {
    "use strict";
    var file = fileChooser.files[0];
    var reader = new FileReader();


Function that populates data from the xml to the form

function populateData(form, xmlDoc){ 
"use strict";
var root = xmlDoc.documentElement;
// get all the customMetaData nodes
var metadataNodes = root.querySelectorAll('customMetaData');
// create an object to store the key/values
var map = {};
// iterate over the nodes and get the key and value to add to the map
  metadataNodes.forEach(function(metadata) {
    var key = metadata.querySelector('key').textContent;
    var value = metadata.querySelector('value').textContent;
    map[key] = value;
  // interate over your form and find the value in the map for that input's name
  for (var i = 0; i <form.elements.length; i++) {
    var input = form.elements[i];
        input.value = map[input.name] || '';     

Listener Event to call the function “handleFileSelection”

fileChooser.addEventListener('change', handleFileSelection, false);