使用JavaScript从XML文件中获取内部元素

时间:2014-11-28 14:08:12

标签: javascript html xml

我有一个带有乒乓球规则的XML文件,我想用JavaScript解析为HTML。继承人的XML:

<rulesection>
        <sectiontitle>A let</sectiontitle>
        <rule>
            <point>2.09.01</point>
            <description>
                The rally shall be a let
            </description>
        <subrule>
            <point>2.09.01.01</point>
            <description>
                if in service the ball, in passing over or around the net assembly, touches it, provided the service is otherwise correct or the ball is obstructed by the receiver or his or her partner;
            </description>
        </subrule>
</rule>
</rulesection>

我有一些JavaScript代码,所以我可以获得sectiontitle,point和description。不幸的是,我似乎无法获得这些子规则,谷歌也不会帮助我。使用我现在的代码,我只得到每个规则部分的第一条规则。

    <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.open("GET", "fuckrules.xml", false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;


var x = xmlDoc.getElementsByTagName("rulesection");
for (i = 0; i < x.length; i++) {
    document.write("<br>");
    document.write(x[i].getElementsByTagName("sectiontitle")[0].childNodes[0].nodeValue);
    document.write("<br>");
    document.write(x[i].getElementsByTagName("point")[0].childNodes[0].nodeValue);
    document.write("<br>");
    document.write(x[i].getElementsByTagName("description")[0].childNodes[0].nodeValue);
}
</script>

我曾尝试使用多个for循环,但我仍然无法获得规则中子规则的要点和描述。如果有人能给我一些非常有帮助的指示:)

1 个答案:

答案 0 :(得分:0)

如果您不介意将jQuery引入项目,这很简单。

假设您的XML已加载到rules变量中:

// iterate over each rulesection
rules.each(function(idx) {
    var s = jQuery(this); // s now refers to a single rulesection node
    var blurp = jQuery('<section class="rulesection" />'); 
    // build up blurp to have the elements you need
    blurp.append('<h1 class="title">' + jQuery('sectiontitle', s).text() + '</h1>');
    // note use of second param to limit matches to 's' node
    // (you can do another .each() on the rules / subrules)
    jQuery('subrule', s).each(function (idx) {
        var sr = jQuery(this); // is the first subrule node
        // do stuff with it...
    });

    // add to the container
    jQuery('#rules').append(blurp);
});

工作JS小提琴:http://jsfiddle.net/tx2fr132/5/