In this article I will explain with an example, how to display XML file with Formatting in HTML page using JavaScript and jQuery.
The XML file will be selected using FileUpload element and its content will be read using HTML5 FileReader and finally the formatted XML file will be displayed using HTML TextArea element.
 
 
HTML Markup
The HTML Markup consists of a FileUpload control (HTML File Input) and a HTML Button.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $("#upload").bind("click", function () {
                var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.xml)$/;
                if (regex.test($("#fileUpload").val().toLowerCase())) {
                    if (typeof (FileReader) != "undefined") {
                        var reader = new FileReader();
                        reader.onload = function (e) {
                            $("#txtXml").val(e.target.result);
                        }
                        reader.readAsText($("#fileUpload")[0].files[0]);
                    } else {
                        alert("This browser does not support HTML5.");
                    }
                } else {
                    alert("Please upload a valid XML file.");
                }
            });
        });
    </script>
    <input type="file" id="fileUpload" />
    <input type="button" id="upload" value="Upload" />
    <hr />
    <textarea id="txtXml" rows="25" cols="40" readonly="readonly" style="border:none; overflow:hidden"></textarea>
</body>
</html>
 
 
Explanation:
Reading the XML File
The XML file is selected in FileUpload control (HTML File Input) and Upload button is clicked. On the click event of the Upload button a JavaScript function is being called.
Inside the function, first a check is performed to verify whether the file is a valid XML or a text file. Then a check is performed to make sure whether the browser supports HTML5 File API.
 
Displaying XML file with Formatting
The contents of the XML file are displayed using an HTML TextArea element whose Borders and Scrollbars are hidden using CSS.
Note: An XML file cannot be rendered in its original format directly using HTML and hence the best element to display its contents is HTML TextArea.
 
 
Screenshot
Display XML file with Formatting in HTML page using JavaScript and jQuery
 
 
Browser Compatibility

The above code has been tested in the following browsers only in versions that support HTML5.

Internet Explorer  FireFox  Chrome  Safari  Opera 

* All browser logos displayed above are property of their respective owners.

 
 
Downloads