Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to upload and parse XML in browser

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?

like image 809
aboutus Avatar asked Jun 25 '17 17:06

aboutus


1 Answers

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

like image 173
Alexander Higgins Avatar answered Oct 15 '22 10:10

Alexander Higgins