使用 JavaScript 从 XML 文件中获取内部元素
Get inner elements from XML file with JavaScript
我有一个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/
相关文章:
- 能够获取元素长度,但不能获取内部 HTML
- 如何使用JS抓取页面以获取内部链接?它也必须递归地完成
- 如何获取内部动态加载图像的元素的高度
- 使用javascript获取内部HTML元素
- 如何在普通 JavaScript 中获取内部子节点的最外层父节点
- 获取内部范围的文本
- 使用 JavaScript 获取内部 HTML 文本时出现问题
- 获取内部 HTML 如已更改
- 如何根据属性 ID 获取内部 html
- 获取内部文本并将其拆分.使用innerHTML和split的Javascript问题
- 使用 JavaScript 从 XML 文件中获取内部元素
- 从动态添加的脚本标记中获取内部 HTML
- 使用 jQuery 从 Chrome 中的 XML 节点获取内部 XML
- 如何使用jquery2.0获取内部HTML
- 获取内部输入<tr>在tbody中标记
- 从类中获取内部 HTML
- 在laravel 5.1上使用此代码获取内部服务器错误500
- 为jsp中的每个循环获取内部隐藏字段的值
- 从不同的id获取内部HTML
- Drupal:Ajaxpost获取内部服务器错误