gpt4 book ai didi

jQuery XML 解析/遍历

转载 作者:数据小太阳 更新时间:2023-10-29 01:39:44 24 4
gpt4 key购买 nike

我有以下 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>

我想做的是循环某一行的每一行。

我尝试这样做是为了获取所有属性 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 值作为属性的 sibling 而不是 child 。看起来更连贯的结构可能是:

<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>

最后,让我们提取主要的 attr id 并将它们绑定(bind)到值中:

<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>

关于jQuery XML 解析/遍历,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1022080/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com