jQuery的XML解析/遍历
我有以下XML的jQuery的XML解析/遍历
<rows>
<row id="5">
<cell>Item1</cell>
<attrs>
<attr>
<id>1</id>
<type>CheckBox</type>
<values>
<value>
<id>10</id>
</value>
<value>
<id>11</id>
</value>
</values>
</attr>
<attr>
<id>2</id>
<type>CheckBox</type>
<values>
<value>
<id>20</id>
</value>
<value>
<id>21</id>
</value>
</values>
</attr>
</attrs>
</row>
</rows>
我想要做的是循环每个一定行的。
我试图做到这一点,以获得所有的attr id,但我也得到了值id。
function fillForm(id){
var theRow = $(theXmlDoc).find('row[id='+id+']').get()
$(theRow).find("attr").each(function(i)
{
alert($(this).find("id").text());
});
}
我也想指出,主要目标是循环每个ATTR事后循环每个值,而我有ATTR的ID。
P.S如果你想到一个更容易/更简单的方式来做到这一点与其他图书馆,我愿意提出建议。
由于提前,
我不清楚你在想什么循环,我觉得你的问题的标签之一是乱码。你说:“我想要做的是循环每一行的某一行。”我想你在那里有一个标签。
无论如何,下面是一些使用jQuery从分析的xml文档中提取数据的示例。评论显示将提醒什么。
我认为问题的一部分是你有id值作为兄弟姐妹,而不是孩子的属性。看起来像一个更连贯的结构可能是:
<rows>
<row id="5">
<cell>Item1</cell>
<attrs>
<attr id="1">
<type>CheckBox</type>
<values>
<value>
<id>10</id>
</value>
<value>
<id>11</id>
</value>
</values>
</attr>
<attr id="2">
<type>CheckBox</type>
<values>
<value>
<id>20</id>
</value>
<value>
<id>21</id>
</value>
</values>
</attr>
</attrs>
</row>
</rows>
但是,如果你不能控制的XML,请忽略该建议。 :-)
好了,这里有穿越的一些样品来获得各种数据:
首先,让我们刚刚获得“项目1”
<script type="text/javascript">
// Item1
$.get('sample.xml', null, function (data, textStatus) {
alert($(data).find('rows row[id=5] cell').text());
}, 'xml');
</script>
现在,我们将得到1和2 :
<script type="text/javascript">
// 1
// 2
$.get('sample.xml', null, function (data, textStatus) {
$(data).find('rows row[id=5] attrs attr > id').each(function(){
alert($(this).text()); // 1, 2
});
}, 'xml');
</script>
最后,让我们拉出主ATTR ID和他们扎入值:
<script type="text/javascript">
// rows row[id=5] attrs attr > id 1 has inner ids of 10,11
// rows row[id=5] attrs attr > id 2 has inner ids of 20,21
$.get('sample.xml', null, function (data, textStatus) {
var out = ''
$(data).find('rows row[id=5] attrs attr > id').each(function(){
out += 'rows row[id=5] attrs attr > id ' + $(this).text();
var innerIds = [];
$(this).siblings('values').find('value id').each(function(){
innerIds.push($(this).text())
});
out += ' has inner Ids of ' + innerIds.join(',') + '\n';
});
alert(out);
}, 'xml');
</script>
这应该
function fillForm(id){
var row = $(theXmlDoc).find('row#+'+ id);
var ids = row.find("attr > id");
ids.each(function(i)
{
alert($(this).text());
});
}
你PS工作。您可以使用xpath之一:
var ids = document.evaluate('//rows/row[@id='+id + ']/attr/id/text()', theXmlDoc, null, XPathResult.ANY_TYPE, null);
它不起作用。 – 2009-06-20 17:47:40
已编辑。对不起,我无法在这里测试。 – 2009-06-20 18:02:51
刚刚有几乎完全相同的问题。 +1 – 2010-05-12 23:19:10