如何在浏览器独立的Javascript中解析嵌套的XML文件?

时间:2015-02-11 11:10:59

标签: javascript html xml nested

我有 XML 文件我希望它在Javascript中解析并在HTML文件中显示内容。我试过跟随javascript代码 -

function loadXMLDoc()
{
    if (window.XMLHttpRequest)
    { // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    }
    else
    { // code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function()
    {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
        {
            xmlDoc = xmlhttp.responseXML;

            var txt = "<ul>";
            var x = xmlhttp.responseXML.documentElement.getElementsByTagName("CONTROLLER"); 
            for (var i = 0; i < x.length; i++) {
}
            txt = txt + "</ul>";
            document.getElementById("myTD").innerHTML = txt;
        }
    };
    xmlhttp.open("GET","console1.xml",true);
    xmlhttp.send();
}

当我用 TITLE 代替 CONTROLLER 时,它会列出XML中存在的所有 TITLE 。但我希望它以嵌套的方式阅读XML。我的XML文件是 -

<?xml version="1.0" encoding="UTF-8"?>
<CONTROLLERS>
    <CONTROLLER>
        <TITLE>User</TITLE>
        <ACTION>
            <LABEL>Create User</LABEL>
            <HTTP_METHOD>POST</HTTP_METHOD>
            <PARAMS>
               <PARAM><NAME>email</NAME></PARAM>
               <PARAM><NAME>user_name</NAME></PARAM>
               <PARAM><NAME>first_name</NAME></PARAM>
               <PARAM><NAME>last_name</NAME></PARAM>
            </PARAMS>
        </ACTION>
        <ACTION>
            <LABEL>Update User</LABEL>
            <HTTP_METHOD>POST</HTTP_METHOD>
            <PARAMS>
               <PARAM><NAME>id</NAME></PARAM>
               <PARAM><NAME>email</NAME></PARAM>
               <PARAM><NAME>user_name</NAME></PARAM>
               <PARAM><NAME>first_name</NAME></PARAM>
               <PARAM><NAME>last_name</NAME></PARAM>
            </PARAMS>
        </ACTION>
    </CONTROLLER>
    <CONTROLLER>
        <TITLE>Admin</TITLE>
        <ACTION>
            <LABEL>Create Admin</LABEL>
            <HTTP_METHOD>POST</HTTP_METHOD>
            <PARAMS>
               <PARAM><NAME>email</NAME></PARAM>
               <PARAM><NAME>admin_name</NAME></PARAM>
               <PARAM><NAME>password</NAME></PARAM>
            </PARAMS>
        </ACTION>
    </CONTROLLER>
</CONTROLLERS>

所以请帮我解析javascript中的嵌套XML文件。

0 个答案:

没有答案