7

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?

1 Answer 1

14

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

Sign up to request clarification or add additional context in comments.

2 Comments

I think in the line var doc = parser.parseFromString( selectedFile, "application/xml"); selectedFile should be replaced with readXml
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.