Using JavaScript to parse an XML file

后端 未结 1 1296
一个人的身影
一个人的身影 2020-12-05 03:21

I am new to Stack OverFlow and coding in general. I am trying to take an XML file and render it in the browser using JavaScript. I have looked around at some sample code of

相关标签:
1条回答
  • 2020-12-05 03:48

    You need to add an onload event listener to the xmlhttprequest before sending the request. Also, you might need to parse the XML with a DOMParser. Anyway, this should work on modern browsers:

    <!DOCTYPE html>
    <html>
        <body>
    
            <script>
                if (window.XMLHttpRequest)
                {// code for IE7+, Firefox, Chrome, Opera, Safari
                    xmlhttp=new XMLHttpRequest();
                }
                else
                {// code for IE6, IE5
                    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
                }
    
    
    
                xmlhttp.onload = function() {
                    var xmlDoc = new DOMParser().parseFromString(xmlhttp.responseText,'text/xml');
    
                    console.log(xmlDoc);
    
                    document.write("<table border='1'>");
                    var x=xmlDoc.getElementsByTagName("CD");
                    for (i=0;i<x.length;i++)
                    { 
                        document.write("<tr><td>");
                        document.write(x[i].getElementsByTagName("c_id")[0].childNodes[0].nodeValue);
                        document.write("</td><td>");
                        document.write(x[i].getElementsByTagName("facebook_id")[0].childNodes[0].nodeValue);
                        document.write("</td></tr>");
                    }
                    document.write("</table>");
    
                }
    
    
                xmlhttp.open("GET","social.xml",false);
                xmlhttp.send();
                </script>
    
        </body>
    </html>
    

    Now, just a couple of things worth mentioning about what you're doing:

    • xmlhttprequest objects have many different parameters that mean a variety of things: readystate, status code, the works. You might benefit looking a bit more into those.

    • document.write should really never be used, ever. In fact, any means of HTML injection should be handled very carefully. You could use a template-based solution common in many MVC-esque frameworks, or mine if you want :)

    0 讨论(0)
提交回复
热议问题