Click here to Skip to main content
15,502,045 members
Articles / Web Development / HTML
Tip/Trick
Posted 23 Oct 2018

Tagged as

Stats

12.4K views
3 bookmarked

And Now... How to Open an XML File in JavaScript for Web

Rate me:
Please Sign up or sign in to vote.
4.00/5 (2 votes)
23 Oct 2018CPOL
How to open an XML file in JavaScript for Web

Reload

Introduction

Hello! This post will show you how to open and show XML files in JavaScript for Web.

This week, I posted "How to Open a JSON File in JavaScript for Web", and I tried for XML (to research my little acknowledgments). For this reason, I posted this article to show "How to open an XML file in JavaScript for Web".

Background

I follow the line of my post and I read something of this:

Code

Now we can train with a local XML variable and parse the XML format into childNodes:

HTML
<!DOCTYPE html>
<html>
    <head>
        <title>XML Test</title>
    </head>
    <body>
        <h1>XML Test</h1>
        <h2>Create a string from a XML array.</h2>
        
        <hr />

        <p id="demo"></p>

        <script>
            function StringToXMLDom(sXML) {
                    var xmlDoc=null;
                    
                    if (window.DOMParser) {
                        parser=new DOMParser();
                        xmlDoc=parser.parseFromString(sXML,"text/xml");
                    } else { // Internet Explorer
                        xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
                        xmlDoc.async="false";
                        xmlDoc.loadXML(sXML);
                    }
                    
                    return xmlDoc;
                }

            var XMLArray = "<bookstore>" +
                    "<book>" +
                        "<title>Everyday Italian</title>" +
                        "<author>Giada De Laurentiis</author>" +
                        "<year>2005</year>" +
                    "</book>" +
                    "<book>" +
                        "<title>La uruguaya</title>" +
                        "<author>Pedro Mairal</author>" +
                        "<year>2016</year>" +
                    "</book>" +
                "</bookstore>";
            
            var tbData = "";
            var xmlData = StringToXMLDom(XMLArray);
            
            if (XMLArray) {
                var tmp = xmlData.getElementsByTagName("book");
                
                for (var i = 0; i < tmp.length; i++) {
                    for (var j = 0; j < tmp[i].childNodes.length; j++) {
                            tbData += tmp[i].childNodes[j].tagName + ": "
                                    + tmp[i].childNodes[j].textContent + "<br />";
                        }
                        
                        tbData += "<br />";
                    }
                
                document.getElementById("demo").innerHTML = tbData;
            } else {
                document.getElementById("demo").innerHTML = "Error!";
            }
        </script>
    </body>
</html>

Well, we can start coding something! Let's write an XML file (I saved it as Books.xml):

XML
<bookstore>
    <book>
        <title>Everyday Italian</title>
        <author>Giada De Laurentiis</author>
        <year>2005</year>
    </book>
    <book>
        <title>La uruguaya</title>
        <author>Pedro Mairal</author>
        <year>2016</year>
    </book>
</bookstore>

Then we can write a WebPage with our JavaScript! Like this:

HTML
<!DOCTYPE html>
<html>
    <head>
        <title>XML Test</title>
    </head>
    <body>
        <h1>XML Test</h1>
        <h2>Create an array from XML string file.</h2>
        
        <hr />
        
        <p id="demo"></p>

        <script>
            function loadXML(callback) {
                    var xobj = new XMLHttpRequest();
                    xobj.overrideMimeType("application/xml");
                    xobj.onreadystatechange = function () {
                            if (xobj.readyState == 4 && xobj.status == "200") {
                                // Required use of an anonymous callback as .open will NOT 
                                // return a value but simply returns undefined in asynchronous mode
                                callback(xobj.responseText);
                            } else {
                                callback("<bookstore><book>
                                <value>Nothing</value></book></bookstore>");
                            }
                        };
                    xobj.open("GET", 
                    "Books.xml", true); // Replace 'my_data' with the path to your file
                    xobj.setRequestHeader("Access-Control-Allow-Origin","*");
                    xobj.send(null);  
                };
            
            function StringToXMLDom(sXML) {
                    var xmlDoc=null;
                    
                    if (window.DOMParser) {
                        parser=new DOMParser();
                        xmlDoc=parser.parseFromString(sXML,"text/xml");
                    } else { // Internet Explorer
                        xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
                        xmlDoc.async="false";
                        xmlDoc.loadXML(sXML);
                    }
                    
                    return xmlDoc;
                }
            
            loadXML(function(response) {
                    var tbData = "";
                    var xmlData = StringToXMLDom(response);
                    
                    if (xmlData) {
                        var tmp = xmlData.getElementsByTagName("book");
                        
                        for (var i = 0; i < tmp.length; i++) {
                            for (var j = 0; j < tmp[i].childNodes.length; j++) {
                                    tbData += tmp[i].childNodes[j].tagName + ": "
                                            + tmp[i].childNodes[j].textContent + "<br />";
                                }
                                
                                tbData += "<br />";
                            }
                        
                        document.getElementById("demo").innerHTML = tbData;
                    } else {
                        document.getElementById("demo").innerHTML = "Error!";
                    }
                });
        </script>
    </body>
</html>

That's It

It's a very quick scripting WebPage where we can handle local XML files. With this method, you can parse the XML into childNodes.

I hope that it'll be useful for you!

If you liked the post, spare some time to give me a vote/comment, it would be appreciated.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Argentina Argentina
I'm a Software Developer. I like to share knowledgements and I worked with C, C++, C#, VB, PHP, Java, and more...

Comments and Discussions

 
Questionxplat Pin
Lucas Vogel25-Oct-18 7:42
professionalLucas Vogel25-Oct-18 7:42 
Nice work! But, what if I'm running this on a Linux machine? Can you give us an example of how to do this using cross-platform modules from, say, NodeJS?
AnswerRe: xplat Pin
Matias Lopez25-Oct-18 9:15
Matias Lopez25-Oct-18 9:15 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.