使用javascript将属性解析为XML

时间:2013-01-16 18:42:47

标签: html xml

我需要使用HTML和javascript解析XML解析。

我的XML:

 <tv_channel id = "1">
        <movie>
            <name>Movie 1</name>
            <time>6:00</time>
        </movie>
        <movie>
            <name>Movie 2</name>
            <time>6:30</time>
        </movie>
   </tv_channel>
    <tv_channel id = "2">
        <movie>
            <name>Movie 3</name>
            <time>11:15</time>
        </movie>
        <movie>
            <name>Movie 4</name>
            <time>13:45</time>
        </movie>
    </tv_channel>

我的Javascript是

function vyberZaner(zaner, nazov, from, to) {
    if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    } else {// code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.open("GET", "XML.xml", false);
    xmlhttp.send();
    xmlDoc = xmlhttp.responseXML;
    var txt = document.getElementById('div_table')
    var content = '';
    content += '<table border=\'1\'>';
    var x = xmlDoc.getElementsByTagName("tv_channel");
    content += '<h1 > ' + nazov + ' </h1>';
    content += ("<td> NAME </td>");
    content += ("<td> GENRE </td>");
        for (i = 0; i < x.length; i++) {
            content += '<tr><td>';
            content += x[i].getElementsByTagName("name")[0].childNodes[0].nodeValue;
            content += '</td><td>';
            content += x[i].getElementsByTagName("time")[0].childNodes[0].nodeValue;
            content += '</td></tr>';
}
    content += '</table>';
    txt.innerHTML = content;
}

输出

Movie 1   6:00
Movie 2   6:00
Movie 3   6:00
Movie 4   6:00

我只需要两个

Movie 1   6:00
Movie 2   6:00

Movie 3   6:00
Movie 4   6:00

这取决于id,但我不知道该怎么做。 我只需要输出像“电影1和电影2”或“电影3和电影4”。用户将选择按钮选择xml,并仅显示id为1或id为2的频道信息及其名称和时间。

1 个答案:

答案 0 :(得分:1)

使用getAttribute方法确定是否为通道ID 1或通道ID 2提取XML,然后输出该内容。在for循环中,使用:

if(x [i] .getAttribute('id')== 1or2){do whatever}

请参阅:http://www.w3schools.com/dom/met_element_getattribute.asp

相关问题