使用Javascript解析XML并创建数组 [英] Parsing XML with Javascript and create array

查看:77
本文介绍了使用Javascript解析XML并创建数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在逐步处理一堆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;
}

问题控制台的结果是

解析TRD3066 tot = TRD3066,1,15,23.1,1 解析DIC72000280 tot = DIC72000280,1,15,278.26,1,DIC72000280,1,15,278.26,1 解析KRE22208 tot = KRE22208,1,15,4.65,1,KRE22208,1,15,4.65,1,KRE22208,1,15,4.65,1

parse TRD3066 tot=TRD3066,1,15,23.1,1 parse DIC72000280 tot=DIC72000280,1,15,278.26,1,DIC72000280,1,15,278.26,1 parse KRE22208 tot=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并创建数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆