问题描述
我正在逐步处理一堆XML,试图在javascript中构建一个数组.
I am stepping through a bunch of XML, trying to build an array within javascript.
XML:
<?xml version="1.0" encoding="utf8" ?>
<session>
<id>12</id>
<name>20130520105033-0-1</name>
<userid>0</userid>
<changed>2013-05-20 11:16:31</changed>
<till>1</till>
<custid>1</custid>
<details>
<item>
<prodcode>TRD3066</prodcode>
<qty>1</qty>
<tax>15</tax>
<uprice>23.1</uprice>
<price>1</price>
</item>
<item>
<prodcode>DIC72000280</prodcode>
<qty>1</qty>
<tax>15</tax>
<uprice>278.26</uprice>
<price>1</price></item>
<item>
<prodcode>KRE22208</prodcode>
<qty>1</qty>
<tax>15</tax>
<uprice>4.65</uprice>
<price>1</price>
</item>
</details>
<comment></comment>
<customer_comment></customer_comment>
</session>
用于解析此内容的Javascript:(在传递了详细信息xml标记之后)
Javascript used to parse this:(after passing the details xml tag)
function parse(details){
var ret=[];var tot=[];
jQuery(details).find("item").each(function(){
ret[0]= jQuery(this).find('prodcode').text();
console.log("parse "+ret[0]);
ret[1]= jQuery(this).find('qty').text();
ret[2]= jQuery(this).find('tax').text();
ret[3]= jQuery(this).find('uprice').text();
ret[4]= jQuery(this).find('price').text();
tot.push(ret);
console.log("tot="+tot);
});
return tot;
}
问题控制台的结果是
解析TRD3066tot = TRD3066,1,15,23.1,1解析DIC72000280tot = DIC72000280,1,15,278.26,1,DIC72000280,1,15,278.26,1解析KRE22208tot = KRE22208,1,15,4.65,1,KRE22208,1,15,4.65,1,KRE22208,1,15,4.65,1
parse TRD3066tot=TRD3066,1,15,23.1,1parse DIC72000280tot=DIC72000280,1,15,278.26,1,DIC72000280,1,15,278.26,1parse KRE22208tot=KRE22208,1,15,4.65,1,KRE22208,1,15,4.65,1,KRE22208,1,15,4.65,1
那是那些夜晚之一,我只是不明白为什么最终tot数组不是所有单独的项目?
It's one of those nights, and I am just not seeing why the end tot array is not all the individual items ??
推荐答案
我认为是导致问题的原因是.each
函数,您应该将其替换为简单的for
循环
I think it is the .each
function that is causing the issue, you should replace it with simple for
loop
var items = jQuery(details).find("item");
for (var i = 0; i < items.length; i++) {
var ret = [];
ret[0] = jQuery(items[i]).find('prodcode').text();
console.log("parse " + ret[0]);
ret[1] = jQuery(items[i]).find('qty').text();
ret[2] = jQuery(items[i]).find('tax').text();
ret[3] = jQuery(items[i]).find('uprice').text();
ret[4] = jQuery(items[i]).find('price').text();
tot.push(ret);
console.log("tot=" + tot);
}
这篇关于使用Javascript解析XML并创建数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!