6

I'm trying to upload an XML file in the browser then parse the XML. On the uploaded file i can see the size correct, but it looks like have no data.

$('#xmlForm').submit(function(event) {
  event.preventDefault();
  var selectedFile = document.getElementById('input').files[0];

  var parser = new DOMParser();
  var doc = parser.parseFromString( selectedFile, "text/xml");
  console.log(doc);
 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="xmlForm">
  <input type="file" id="input">
  <input type="submit">
 </form>

The parser basically says to me: "The document is empty"

What am i missing?

aboutus
  • 229
  • 4
  • 13

1 Answers1

13

The parser basically says to me: "The document is empty"

What am i missing

In this line you are passing the file to the parser.parseFromString method which is expecting a string containing the markup to parse and not a file.

var doc = parser.parseFromString( selectedFile, "text/xml");

By all means not a complete example, this code will read the contents of the file using a FileReader

<!DOCTYPE html>
<html>
<head>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
    </script>
    <title></title>
</head>
<body>
    <form id="xmlForm" name="xmlForm">
        <input id="input" type="file"> <input type="submit">
    </form>
    <script>
       var readXml=null;
       $('#xmlForm').submit(function(event) {
           event.preventDefault();
           var selectedFile = document.getElementById('input').files[0];
           console.log(selectedFile);
           var reader = new FileReader();
           reader.onload = function(e) {
               readXml=e.target.result;
               console.log(readXml);
               var parser = new DOMParser();
               var doc = parser.parseFromString(readXml, "application/xml");
               console.log(doc);
           }
           reader.readAsText(selectedFile);

       });
    </script>
</body>
</html>

See this: How to read text file in JavaScript

Alexander Higgins
  • 6,765
  • 1
  • 23
  • 41
  • I think in the line `var doc = parser.parseFromString( selectedFile, "application/xml");` selectedFile should be replaced with readXml – foolo Oct 05 '18 at 16:35
  • Selected file refers to the file. This is the OP's problem. you cannot pass a `file` to the method `parser.parseFromString(string value, string contentType)` The argument `value` expects a string, not a file. – Alexander Higgins Oct 26 '22 at 01:17