我有以下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 ids,但我也获得了值ids。
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时循环每个值。
附注:如果你想出一种更简单的方法来使用其他库,我欢迎你的建议。
提前谢谢你,
发布于 2009-06-20 18:46:51
我不清楚你想要遍历的是什么,我想你问题中的一个标签是乱码。你说:“我想做的是循环某一行的每一行。”我想你在那里面有个标签。
不管怎样,下面是一些使用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,请忽略该建议。:-)
好的,下面是一些遍历各种数据的示例:
首先让我们得到"Item1“
<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>
最后,让我们提取主属性ids并将它们绑定到值中:
<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>
发布于 2009-06-20 17:42:10
这对你来说应该是可行的
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 );
https://stackoverflow.com/questions/1022080
复制相似问题