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

Get inner elements from XML file with JavaScript

本文关键字:获取 内部 元素 文件 JavaScript XML 使用      更新时间:2023-09-26

我有一个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代码,所以我可以获得部分标题,要点和描述。不幸的是,我似乎无法获得子规则,谷歌不会帮助我解决这个问题。使用我现在拥有的代码,我只得到每个规则部分的第一条规则。

    <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 循环,但我仍然无法获得规则内子规则的点和描述。如果有人能给我一些指示,那将是非常有帮助的:)

如果你不介意在你的项目中引入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/