使用 Javascript 将 XML 转换为 CSV

XML to CSV Conversion using Javascript(使用 Javascript 将 XML 转换为 CSV)
本文介绍了使用 Javascript 将 XML 转换为 CSV的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我正在寻求一些帮助,尝试将从亚马逊产品 API 检索到的 XML 转换为 CSV(逗号分隔值)格式.

我在这里找到了一个类似的主题:XML 到 CSV 转换问题,但它使用PHP,我想改用 javascript.

这是我所拥有的示例:

<?xml version="1.0" encoding="UTF-8"?><ItemLookupResponse xmlns="http://webservices.amazon.com/AWSECommerceService/2011-08-01"><操作请求><RequestId>1k75f474-85ff-464a-al93-659ol460caee</RequestId><论据><参数名称="操作"值="ItemLookup"/><参数名称="服务" 值="AWSECommerceService"/><参数名称="签名"值="lImNXr6R4c2t376ghMnMmjUPR4eY6755XzH41pXGH0P="/><参数名称="AssociateTag" 值="oiuig-20"/><参数名称="ItemId" 值="B007EHI1DK"/><参数名称="AWSAccessKeyId" 值="DIY7F4M00OF6I7TRD3VA"/><参数名称="时间戳"值="2013-01-04T05:23:20Z"/><参数名称=响应组"值=大"/></参数><RequestProcessingTime>0.0359500000000000</RequestProcessingTime></操作请求><项目><请求><IsValid>True</IsValid><ItemLookupRequest><IdType>ASIN</IdType><ItemId>B007EHI1DK</ItemId><ResponseGroup>大</ResponseGroup><VariationPage>全部</VariationPage></ItemLookupRequest></请求><项目><ASIN>B007EHI1DK</ASIN><DetailPageURL>http://www.amazon.com/Panasonic-TY-ER3D4MU-Active-Shutter-Eyewear/dp/B007EHI1DK%3FSubscriptionId%3DIY7F4M00OF6I7TRD3VAS%26tag%3Daztag-20%26linkCode%3Dxm2%26camp%3D2025%26creative%3D165953%26creativeASIN%3DB007EHI1DK</DetailPageURL><项目链接><物品链接><描述>技术细节</描述><网址>http://www.amazon.com/Panasonic-TY-ER3D4MU-Active-Shutter-Eyewear/dp/tech-data/B007EHI1DK%3FSubscriptionId%3DIY7F4M00OF6I7TRD3VAS%26tag%3Daztag-20%26linkCode%3Dxm2%26camp%3D2025%26creative%3D386001%26creativeASIN%3DB007EHI1DK</URL></ItemLink><物品链接><描述>添加到婴儿注册表</描述><网址>http://www.amazon.com/gp/registry/baby/add-item.html%3Fasin.0%3DB007EHI1DK%26SubscriptionId%3DIY7F4M00OF6I7TRD3VAS%26tag%3Daztag-20%26linkCode%3Dxm2%26camp%3D2025%26creative%3D386001%26creativeASIN%3DB007EHI1DK</URL></ItemLink><物品链接><描述>添加到婚礼登记处</描述><网址>http://www.amazon.com/gp/registry/wedding/add-item.html%3Fasin.0%3DB007EHI1DK%26SubscriptionId%3DIY7F4M00OF6I7TRD3VAS%26tag%3Daztag-20%26linkCode%3Dxm2%26camp%3D2025%26creative%3D386001%26creativeASIN%3DB007EHI1DK</URL></ItemLink><物品链接><描述>添加到愿望清单</描述><网址>http://www.amazon.com/gp/registry/wishlist/add-item.html%3Fasin.0%3DB007EHI1DK%26SubscriptionId%3DIY7F4M00OF6I7TRD3VAS%26tag%3Daztag-20%26linkCode%3Dxm2%26camp%3D2025%26creative%3D386001%26creativeASIN%3DB007EHI1DK</URL></ItemLink><物品链接><描述>告诉朋友</描述><URL>http://www.amazon.com/gp/pdp/taf/B007EHI1DK%3FSubscriptionId%3DIY7F4M00OF6I7TRD3VAS%26tag%3Daztag-20%26linkCode%3Dxm2%26camp%3D2025%26creative%3D386001%26creativeASIN%3DB007EHI1DK<;</ItemLink><物品链接><描述>所有顾客评论</描述><URL>http://www.amazon.com/review/product/B007EHI1DK%3FSubscriptionId%3DIY7F4M00OF6I7TRD3VAS%26tag%3Daztag-20%26linkCode%3Dxm2%26camp%3D2025%26creative%3D386001%26creativeASIN%3DB007EHI1DK</URL></ItemLink><物品链接><描述>所有优惠</描述><URL>http://www.amazon.com/gp/offer-listing/B007EHI1DK%3FSubscriptionId%3DIY7F4M00OF6I7TRD3VAS%26tag%3Daztag-20%26linkCode%3Dxm2%26camp%3D2025%26creative%3D386001%26creativeASIN%3DB007EHI1DK<;</ItemLink></ItemLinks><小图像><URL>http://ecx.images-amazon.com/images/I/31pKDguukTL._SL75_.jpg</URL><高度单位="像素">50</高度><宽度单位="像素">75</宽度></小图像><中型图像><URL>http://ecx.images-amazon.com/images/I/31pKDguukTL._SL160_.jpg</URL><高度单位="像素">107</高度><宽度单位="像素">160</宽度></MediumImage><大图><URL>http://ecx.images-amazon.com/images/I/31pKDguukTL.jpg</URL><高度单位="像素">333</高度><宽度单位="像素">500</宽度></大图><图像集><ImageSet 类别="主要"><样本图像><URL>http://ecx.images-amazon.com/images/I/31pKDguukTL._SL30_.jpg</URL><高度单位="像素">20</高度><宽度单位="像素">30</宽度></SwatchImage><小图像><URL>http://ecx.images-amazon.com/images/I/31pKDguukTL._SL75_.jpg</URL><高度单位="像素">50</高度><宽度单位="像素">75</宽度></小图像><缩略图><URL>http://ecx.images-amazon.com/images/I/31pKDguukTL._SL75_.jpg</URL><高度单位="像素">50</高度><宽度单位="像素">75</宽度></缩略图图像><小图像><URL>http://ecx.images-amazon.com/images/I/31pKDguukTL._SL110_.jpg</URL><高度单位="像素">73</高度><宽度单位="像素">110</宽度></TinyImage><中型图像><URL>http://ecx.images-amazon.com/images/I/31pKDguukTL._SL160_.jpg</URL><高度单位="像素">107</高度><宽度单位="像素">160</宽度></MediumImage><大图><URL>http://ecx.images-amazon.com/images/I/31pKDguukTL.jpg</URL><高度单位="像素">333</高度><宽度单位="像素">500</宽度></大图></图像集><ImageSet 类别="变体"><样本图像><URL>http://ecx.images-amazon.com/images/I/31dSwH5PnjL._SL30_.jpg</URL><高度单位="像素">20</高度><宽度单位="像素">30</宽度></SwatchImage><小图像><URL>http://ecx.images-amazon.com/images/I/31dSwH5PnjL._SL75_.jpg</URL><高度单位="像素">50</高度><宽度单位="像素">75</宽度></小图像><缩略图><URL>http://ecx.images-amazon.com/images/I/31dSwH5PnjL._SL75_.jpg</URL><高度单位="像素">50</高度><宽度单位="像素">75</宽度></缩略图图像><小图像><URL>http://ecx.images-amazon.com/images/I/31dSwH5PnjL._SL110_.jpg</URL><高度单位="像素">73</高度><宽度单位="像素">110</宽度></TinyImage><中型图像><URL>http://ecx.images-amazon.com/images/I/31dSwH5PnjL._SL160_.jpg</URL><高度单位="像素">107</高度><宽度单位="像素">160</宽度></MediumImage><大图><URL>http://ecx.images-amazon.com/images/I/31dSwH5PnjL.jpg</URL><高度单位="像素">333</高度><宽度单位="像素">500</宽度></大图></图像集><ImageSet 类别="变体"><样本图像><URL>http://ecx.images-amazon.com/images/I/31irEbzxdgL._SL30_.jpg</URL><高度单位="像素">20</高度><宽度单位="像素">30</宽度></SwatchImage><小图像><URL>http://ecx.images-amazon.com/images/I/31irEbzxdgL._SL75_.jpg</URL><高度单位="像素">50</高度><宽度单位="像素">75</宽度></小图像><缩略图><URL>http://ecx.images-amazon.com/images/I/31irEbzxdgL._SL75_.jpg</URL><高度单位="像素">50</高度><宽度单位="像素">75</宽度></缩略图图像><小图像><URL>http://ecx.images-amazon.com/images/I/31irEbzxdgL._SL110_.jpg</URL><高度单位="像素">73</高度><宽度单位="像素">110</宽度></TinyImage><中型图像><URL>http://ecx.images-amazon.com/images/I/31irEbzxdgL._SL160_.jpg</URL><高度单位="像素">107</高度><宽度单位="像素">160</宽度></MediumImage><大图><URL>http://ecx.images-amazon.com/images/I/31irEbzxdgL.jpg</URL><高度单位="像素">333</高度><宽度单位="像素">500</宽度></大图></图像集></图像集><项目属性><装订>电子</装订><品牌>松下</品牌><目录编号列表><CatalogNumberListElement>TYER3D4M</CatalogNumberListElement><CatalogNumberListElement>TYER3D4MU</CatalogNumberListElement><CatalogNumberListElement>TY-ER3D4MU</CatalogNumberListElement></目录编号列表><颜色>一种颜色</颜色><部门>电子</部门><EAN>0885170075207</EAN><EAN 列表><EANListElement>0885170075207</EANListElement></EANList><Feature>轻量级主动式快门 3D 眼镜</Feature><特点>USB充电</特点><功能>RF兼容</功能><IsAutographed>0</IsAutographed><IsMemorabilia>0</IsMemorabilia><物品尺寸><Height Units="hundredths-inches">170</Height><长度单位="hundredths-inches">340</长度><Weight Units="hundredths-pounds">10</Weight><Width Units="hundredths-inches">670</Width></ItemDimensions><标签>松下</标签><价格清单><金额>7995</金额><CurrencyCode>USD</CurrencyCode><FormattedPrice>$79.95</FormattedPrice></列表价格><制造商>松下</制造商><型号>TY-ER3D4MU</型号><MPN>TY-ER3D4MU</MPN><NumberOfItems>1</NumberOfItems><包装尺寸><Height Units="hundredths-inches">240</Height><长度单位="hundredths-inches">690</长度><Weight Units="hundredths-pounds">30</Weight><Width Units="hundredths-inches">350</Width></包装尺寸><PackageQuantity>1</PackageQuantity><零件编号>TY-ER3D4MU</零件编号><ProductGroup>CE</ProductGroup><ProductTypeName>CONSUMER_ELECTRONICS</ProductTypeName><出版商>松下</出版商><尺寸>一个尺寸</尺寸><SKU>292782</SKU><工作室>松下</工作室><标题>松下 VIERA TY-ER3D4MU 主动快门 3D 眼镜</标题><UPC>885170075207</UPC><UPC 列表><UPCListElement>885170075207</UPCListElement></UPCList></ItemAttributes><报价摘要><新品最低价><金额>5400</金额><CurrencyCode>USD</CurrencyCode><FormattedPrice>$54.00</FormattedPrice></最低新价格><最低使用价格><金额>4294</金额><CurrencyCode>USD</CurrencyCode><FormattedPrice>$42.94</FormattedPrice></最低使用价格><TotalNew>24</TotalNew><TotalUsed>18</TotalUsed><TotalCollectible>0</TotalCollectible><TotalRefurbished>0</TotalRefurbished></报价摘要><优惠><TotalOffers>1</TotalOffers><TotalOfferPages>1</TotalOfferPages><MoreOffersUrl>http://www.amazon.com/gp/offer-listing/B007EHI1DK%3FSubscriptionId%3DIY7F4M00OF6I7TRD3VAS%26tag%3Daztag-20%26linkCode%3Dxm2%26camp%3D2025%26creative%3D386001%26creativeASIN%3DB007UrHI&lgt;1;<优惠><优惠属性><条件>新的</条件></OfferAttributes><优惠清单><OfferListingId>rkyW%2Bed7Qb8t28tJRRHkKizuk2CxNF4SI6W9XAnbXI8JX%2FJNpUY%2B8zqnnNRe3Vt2l%2B8rUMqypquQnAE66PYmf32dJeor6DifXvXKscwOqyrLwgFZORqmDg%3D%3D<<价格><金额>5851</金额><CurrencyCode>USD</CurrencyCode><FormattedPrice>$58.51</FormattedPrice></价格><节省的金额><金额>2144</金额><CurrencyCode>USD</CurrencyCode><FormattedPrice>$21.44</FormattedPrice></节省的金额><PercentageSaved>27</PercentageSaved><可用性>通常在 24 小时内发货</Availability><可用性属性><AvailabilityType>现在</AvailabilityType><MinimumHours>0</MinimumHours><MaximumHours>0</MaximumHours></可用性属性><IsEligibleForSuperSaverShipping>1</IsEligibleForSuperSaverShipping></OfferListing></优惠></优惠><客户评价><IFrameURL>http://www.amazon.com/reviews/iframe?akid=AKIAIBT3ANF6TOEOKXVA&amp;alinkCode=xm2&amp;asin=B007EHI1DK&amp;atag=aztag-20&amp;exp=2013-01-05T05%3A23%3A21Z&amp;v=2&sig=yz1U1nT8mWjFGauK3umnsOqp9BTzWwGOAAiLCyZ%2BEPM%3D</IFrameURL><HasReviews>真实</HasReviews></客户评论><社论评论><社论评论><来源>产品描述</来源><内容>&lt;strong&gt;3D播放类型:&lt;/strong&gt;主动快门 3D 方法&lt;br/&gt;&lt;strong&gt;透光率方法:&lt;/strong&gt;RF(蓝牙)/全高清 3D 眼镜标准兼容&lt;br/&gt;&lt;strong&gt;电池类型:&lt;/strong&gt;锂离子聚合物充电电池&lt;br/&gt;&lt;strong&gt;电池续航时间:&lt;/strong&gt;电池充满 30 分钟可运行约 30 小时(电池充电 2 分钟可运行约 3 小时)&lt;em&gt;*电池使用时间将根据总使用时间随充电/放电循环次数而变化 &lt;/em&gt;&lt;br/&gt;&lt;strong&gt;包装包括:&lt;/强&gt;1 副眼镜 &lt;br/&gt;注意:这些眼镜仅兼容 2012 VIERA 高清电视&lt;br/&gt;&lt;br/&gt;&lt;div style="text-align: left;"&gt;&lt;strong&gt;配件兼容性表&lt;br/&gt;&lt;/strong&gt;&lt;/div>&lt;img height="375" src="http://g-ecx.images-amazon.com/images/G/01/electronics/Cat500/Panasonic/2012/accessory_compatibility_2._V138249826_.gif" width="650"/&gt;&lt;br/&gt;&lt;br/&gt;</Content><IsLinkSuppressed>0</IsLinkSuppressed></社论评论></社论评论><类似产品><类似产品><ASIN>B007K9P7H0</ASIN><标题>三星 SSG-4100GB 3D 主动式眼镜 2012 款 - 黑色</标题></类似产品><类似产品><ASIN>B00752VKSC</ASIN><标题>松下 VIERA TC-P55ST50 55 英寸 1080p 600Hz 全高清 3D 等离子电视</标题></类似产品><类似产品><ASIN>B00752R4PK</ASIN><标题>松下 DMP-BDT220 集成 Wi-Fi 3D 蓝光 DVD 播放器</标题></类似产品><类似产品><ASIN>B00752VKFA</ASIN><标题>松下 VIERA TC-P55GT50 55 英寸 1080p 600Hz 全高清 3D 等离子电视</标题></类似产品><类似产品><ASIN>B00752VL8G</ASIN><标题>松下 VIERA TC-P60GT50 60 英寸 1080p 600Hz 全高清 3D 等离子电视</标题></类似产品></类似产品><浏览节点><浏览节点><BrowseNodeId>3224438011</BrowseNodeId><名称>3D眼镜</名称><祖先><浏览节点><BrowseNodeId>172532</BrowseNodeId><名称>音频&amp;视频配件</名称><祖先><浏览节点><BrowseNodeId>281407</BrowseNodeId><名称>配饰&amp;耗材</名称><祖先><浏览节点><BrowseNodeId>493964</BrowseNodeId><名称>类别</名称><IsCategoryRoot>1</IsCategoryRoot><祖先><浏览节点><BrowseNodeId>172282</BrowseNodeId><名称>电子</名称></浏览节点></祖先></浏览节点></祖先></浏览节点></祖先></浏览节点></祖先></浏览节点><浏览节点><BrowseNodeId>1288264011</BrowseNodeId><名称>所有产品</名称><祖先><浏览节点><BrowseNodeId>1267878011</BrowseNodeId><名称>产品</名称><IsCategoryRoot>1</IsCategoryRoot><祖先><浏览节点><BrowseNodeId>1267877011</BrowseNodeId></浏览节点></祖先></浏览节点></祖先></浏览节点><浏览节点><BrowseNodeId>3545110011</BrowseNodeId><名称>家庭娱乐</名称><儿童><浏览节点><BrowseNodeId>3547652011</BrowseNodeId><名称>蓝光播放器</名称></浏览节点><浏览节点><BrowseNodeId>3547650011</BrowseNodeId><名称>DVD播放器</名称></浏览节点><浏览节点><BrowseNodeId>6183878011</BrowseNodeId><名称>家庭影院投影仪</名称></浏览节点><浏览节点><BrowseNodeId>1294446011</BrowseNodeId><名字>电视</名字></浏览节点><浏览节点><BrowseNodeId>6183893011</BrowseNodeId><名称>电视调谐器和接收器</名称></浏览节点></儿童><祖先><浏览节点><BrowseNodeId>1294447011</BrowseNodeId><名称>电子</名称><祖先><浏览节点><BrowseNodeId>1267878011</BrowseNodeId><名称>产品</名称><IsCategoryRoot>1</IsCategoryRoot><祖先><浏览节点><BrowseNodeId>1267877011</BrowseNodeId></浏览节点></祖先></浏览节点></祖先></浏览节点></祖先></浏览节点><浏览节点><BrowseNodeId>1293319011</BrowseNodeId><名称>电子</名称><祖先><浏览节点><BrowseNodeId>1267879011</BrowseNodeId><名称>特殊功能</名称><祖先><浏览节点><BrowseNodeId>1267877011</BrowseNodeId></浏览节点></祖先></浏览节点></祖先></浏览节点></浏览节点></项目></物品></ItemLookupResponse>

我正在尝试使用 Javascript 将此数据格式化为 CSV 格式的表格.

有人可以帮忙吗?

提前致谢!普拉尼

解决方案

经过长时间的调查,我发现了一些可能对你有帮助的东西.

从重新发明轮子是如此愚蠢和耗时的任务开始,我一直在寻找其他优秀程序员已经在互联网上构建的东西.

不幸的是,我无法找到一个直接将 XML 转换为 CSV 的转换器作为您在 PHP 中提供的示例.

在我的工作示例中,XML 必须首先从 JSON 传递,如下所示:

  • xml2json => json2csv

我在这里和那里拿了一些片段,我将在此答案的末尾添加我实际用于构建演示的所有代码片段的参考.通过这种方式,您将能够获得一个漂亮而干净的文档,这将有助于您改进此工具.

这里是一个简单的演示:

function xmlTocsv() {var data = $("#xmlArea").val();var xml = "";if (data !== null && data.trim().length !== 0) {尝试 {xml = $.parseXML(数据);} 抓住 (e) {扔 e;}var x2js = 新 X2JS();数据 = x2js.xml2json(xml);jsonTocsvbyjson(数据);}}函数 jsonTocsvbyjson(data, returnFlag) {arr = [];标志=真;变量头 = "";变种内容=";var headFlag = true;尝试 {var type1 = 数据类型;如果(类型1!=对象"){数据 = processJSON($.parseJSON(data));} 别的 {数据 = processJSON(数据);}} 抓住 (e) {if (returnFlag === undefined || !returnFlag) {console.error("转换为 CSV 时出错");} 别的 {console.error("转换错误:" + e);}返回假;}$.each(数据,函数(k,值){如果 (k % 2 === 0) {如果(头标志){如果(值!=结束"){标题+=值+,";} 别的 {//从字符串中删除最后一个冒号header = header.substring(0, header.length - 1);头旗 = 假;}}} 别的 {如果(值!=结束"){var temp = 数据[k - 1];if (header.search(temp) != -1) {内容+=价值+,";}} 别的 {//从字符串中删除最后一个冒号内容 = content.substring(0, content.length - 1);内容 += "
";}}});if (returnFlag === undefined || !returnFlag) {$("#csvArea").val(header + "
" + content);} 别的 {返回(标题+
"+内容);}}函数处理JSON(数据){$.each(数据,函数(k,data1){var type1 = typeof data1;if (type1 == "object") {标志=假;处理JSON(数据1);arr.push("结束");arr.push("结束");} 别的 {arr.push(k, data1);}});返回 arr;}

<!DOCTYPE html><html><头><script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js'></script><script type='text/javascript' src="https://cdn.rawgit.com/abdmob/x2js/master/xml2json.js"></script><script type="text/javascript" src="script.js"></script></头><身体><h1>XML2CSV 演示</h1><按钮 id="convertToXmlBtn" onclick="xmlTocsv()">XML =>CSV</按钮>

<h4>XML:</h4><textarea id="xmlArea" cols="55" rows="15"></textarea></div>

<h4>CSV:</h4><textarea id="csvArea" cols="55" rows="15"></textarea></div></身体></html>

参考资料:

  • XML TO CSV 转换器
  • x2js - XML 到 JSON,反之亦然 JavaScript

实用程序:

  • Working Plunkr

I am looking for some help trying to convert XML retrieved from Amazon Product API to convert it into CSV(Comma Separated Value) format.

I found a similar topic here: XML to CSV conversion issue but it uses PHP, and I want to use javascript instead.

Here is a sample of what I have:

<?xml version="1.0" encoding="UTF-8"?>
<ItemLookupResponse xmlns="http://webservices.amazon.com/AWSECommerceService/2011-08-01">
  <OperationRequest>
    <RequestId>1k75f474-85ff-464a-al93-659ol460caee</RequestId>
    <Arguments>
      <Argument Name="Operation" Value="ItemLookup" />
      <Argument Name="Service" Value="AWSECommerceService" />
      <Argument Name="Signature" Value="lImNXr6R4c2t376ghMnMmjUPR4eY6755XzH41pXGH0P=" />
      <Argument Name="AssociateTag" Value="oiuig-20" />
      <Argument Name="ItemId" Value="B007EHI1DK" />
      <Argument Name="AWSAccessKeyId" Value="DIY7F4M00OF6I7TRD3VA" />
      <Argument Name="Timestamp" Value="2013-01-04T05:23:20Z" />
      <Argument Name="ResponseGroup" Value="Large" />
    </Arguments>
    <RequestProcessingTime>0.0359500000000000</RequestProcessingTime>
  </OperationRequest>
  <Items>
    <Request>
      <IsValid>True</IsValid>
      <ItemLookupRequest>
        <IdType>ASIN</IdType>
        <ItemId>B007EHI1DK</ItemId>
        <ResponseGroup>Large</ResponseGroup>
        <VariationPage>All</VariationPage>
      </ItemLookupRequest>
    </Request>
    <Item>
      <ASIN>B007EHI1DK</ASIN>
      <DetailPageURL>http://www.amazon.com/Panasonic-TY-ER3D4MU-Active-Shutter-Eyewear/dp/B007EHI1DK%3FSubscriptionId%3DIY7F4M00OF6I7TRD3VAS%26tag%3Daztag-20%26linkCode%3Dxm2%26camp%3D2025%26creative%3D165953%26creativeASIN%3DB007EHI1DK</DetailPageURL>
      <ItemLinks>
        <ItemLink>
          <Description>Technical Details</Description>
          <URL>http://www.amazon.com/Panasonic-TY-ER3D4MU-Active-Shutter-Eyewear/dp/tech-data/B007EHI1DK%3FSubscriptionId%3DIY7F4M00OF6I7TRD3VAS%26tag%3Daztag-20%26linkCode%3Dxm2%26camp%3D2025%26creative%3D386001%26creativeASIN%3DB007EHI1DK</URL>
        </ItemLink>
        <ItemLink>
          <Description>Add To Baby Registry</Description>
          <URL>http://www.amazon.com/gp/registry/baby/add-item.html%3Fasin.0%3DB007EHI1DK%26SubscriptionId%3DIY7F4M00OF6I7TRD3VAS%26tag%3Daztag-20%26linkCode%3Dxm2%26camp%3D2025%26creative%3D386001%26creativeASIN%3DB007EHI1DK</URL>
        </ItemLink>
        <ItemLink>
          <Description>Add To Wedding Registry</Description>
          <URL>http://www.amazon.com/gp/registry/wedding/add-item.html%3Fasin.0%3DB007EHI1DK%26SubscriptionId%3DIY7F4M00OF6I7TRD3VAS%26tag%3Daztag-20%26linkCode%3Dxm2%26camp%3D2025%26creative%3D386001%26creativeASIN%3DB007EHI1DK</URL>
        </ItemLink>
        <ItemLink>
          <Description>Add To Wishlist</Description>
          <URL>http://www.amazon.com/gp/registry/wishlist/add-item.html%3Fasin.0%3DB007EHI1DK%26SubscriptionId%3DIY7F4M00OF6I7TRD3VAS%26tag%3Daztag-20%26linkCode%3Dxm2%26camp%3D2025%26creative%3D386001%26creativeASIN%3DB007EHI1DK</URL>
        </ItemLink>
        <ItemLink>
          <Description>Tell A Friend</Description>
          <URL>http://www.amazon.com/gp/pdp/taf/B007EHI1DK%3FSubscriptionId%3DIY7F4M00OF6I7TRD3VAS%26tag%3Daztag-20%26linkCode%3Dxm2%26camp%3D2025%26creative%3D386001%26creativeASIN%3DB007EHI1DK</URL>
        </ItemLink>
        <ItemLink>
          <Description>All Customer Reviews</Description>
          <URL>http://www.amazon.com/review/product/B007EHI1DK%3FSubscriptionId%3DIY7F4M00OF6I7TRD3VAS%26tag%3Daztag-20%26linkCode%3Dxm2%26camp%3D2025%26creative%3D386001%26creativeASIN%3DB007EHI1DK</URL>
        </ItemLink>
        <ItemLink>
          <Description>All Offers</Description>
          <URL>http://www.amazon.com/gp/offer-listing/B007EHI1DK%3FSubscriptionId%3DIY7F4M00OF6I7TRD3VAS%26tag%3Daztag-20%26linkCode%3Dxm2%26camp%3D2025%26creative%3D386001%26creativeASIN%3DB007EHI1DK</URL>
        </ItemLink>
      </ItemLinks>
      <SmallImage>
        <URL>http://ecx.images-amazon.com/images/I/31pKDguukTL._SL75_.jpg</URL>
        <Height Units="pixels">50</Height>
        <Width Units="pixels">75</Width>
      </SmallImage>
      <MediumImage>
        <URL>http://ecx.images-amazon.com/images/I/31pKDguukTL._SL160_.jpg</URL>
        <Height Units="pixels">107</Height>
        <Width Units="pixels">160</Width>
      </MediumImage>
      <LargeImage>
        <URL>http://ecx.images-amazon.com/images/I/31pKDguukTL.jpg</URL>
        <Height Units="pixels">333</Height>
        <Width Units="pixels">500</Width>
      </LargeImage>
      <ImageSets>
        <ImageSet Category="primary">
          <SwatchImage>
            <URL>http://ecx.images-amazon.com/images/I/31pKDguukTL._SL30_.jpg</URL>
            <Height Units="pixels">20</Height>
            <Width Units="pixels">30</Width>
          </SwatchImage>
          <SmallImage>
            <URL>http://ecx.images-amazon.com/images/I/31pKDguukTL._SL75_.jpg</URL>
            <Height Units="pixels">50</Height>
            <Width Units="pixels">75</Width>
          </SmallImage>
          <ThumbnailImage>
            <URL>http://ecx.images-amazon.com/images/I/31pKDguukTL._SL75_.jpg</URL>
            <Height Units="pixels">50</Height>
            <Width Units="pixels">75</Width>
          </ThumbnailImage>
          <TinyImage>
            <URL>http://ecx.images-amazon.com/images/I/31pKDguukTL._SL110_.jpg</URL>
            <Height Units="pixels">73</Height>
            <Width Units="pixels">110</Width>
          </TinyImage>
          <MediumImage>
            <URL>http://ecx.images-amazon.com/images/I/31pKDguukTL._SL160_.jpg</URL>
            <Height Units="pixels">107</Height>
            <Width Units="pixels">160</Width>
          </MediumImage>
          <LargeImage>
            <URL>http://ecx.images-amazon.com/images/I/31pKDguukTL.jpg</URL>
            <Height Units="pixels">333</Height>
            <Width Units="pixels">500</Width>
          </LargeImage>
        </ImageSet>
        <ImageSet Category="variant">
          <SwatchImage>
            <URL>http://ecx.images-amazon.com/images/I/31dSwH5PnjL._SL30_.jpg</URL>
            <Height Units="pixels">20</Height>
            <Width Units="pixels">30</Width>
          </SwatchImage>
          <SmallImage>
            <URL>http://ecx.images-amazon.com/images/I/31dSwH5PnjL._SL75_.jpg</URL>
            <Height Units="pixels">50</Height>
            <Width Units="pixels">75</Width>
          </SmallImage>
          <ThumbnailImage>
            <URL>http://ecx.images-amazon.com/images/I/31dSwH5PnjL._SL75_.jpg</URL>
            <Height Units="pixels">50</Height>
            <Width Units="pixels">75</Width>
          </ThumbnailImage>
          <TinyImage>
            <URL>http://ecx.images-amazon.com/images/I/31dSwH5PnjL._SL110_.jpg</URL>
            <Height Units="pixels">73</Height>
            <Width Units="pixels">110</Width>
          </TinyImage>
          <MediumImage>
            <URL>http://ecx.images-amazon.com/images/I/31dSwH5PnjL._SL160_.jpg</URL>
            <Height Units="pixels">107</Height>
            <Width Units="pixels">160</Width>
          </MediumImage>
          <LargeImage>
            <URL>http://ecx.images-amazon.com/images/I/31dSwH5PnjL.jpg</URL>
            <Height Units="pixels">333</Height>
            <Width Units="pixels">500</Width>
          </LargeImage>
        </ImageSet>
        <ImageSet Category="variant">
          <SwatchImage>
            <URL>http://ecx.images-amazon.com/images/I/31irEbzxdgL._SL30_.jpg</URL>
            <Height Units="pixels">20</Height>
            <Width Units="pixels">30</Width>
          </SwatchImage>
          <SmallImage>
            <URL>http://ecx.images-amazon.com/images/I/31irEbzxdgL._SL75_.jpg</URL>
            <Height Units="pixels">50</Height>
            <Width Units="pixels">75</Width>
          </SmallImage>
          <ThumbnailImage>
            <URL>http://ecx.images-amazon.com/images/I/31irEbzxdgL._SL75_.jpg</URL>
            <Height Units="pixels">50</Height>
            <Width Units="pixels">75</Width>
          </ThumbnailImage>
          <TinyImage>
            <URL>http://ecx.images-amazon.com/images/I/31irEbzxdgL._SL110_.jpg</URL>
            <Height Units="pixels">73</Height>
            <Width Units="pixels">110</Width>
          </TinyImage>
          <MediumImage>
            <URL>http://ecx.images-amazon.com/images/I/31irEbzxdgL._SL160_.jpg</URL>
            <Height Units="pixels">107</Height>
            <Width Units="pixels">160</Width>
          </MediumImage>
          <LargeImage>
            <URL>http://ecx.images-amazon.com/images/I/31irEbzxdgL.jpg</URL>
            <Height Units="pixels">333</Height>
            <Width Units="pixels">500</Width>
          </LargeImage>
        </ImageSet>
      </ImageSets>
      <ItemAttributes>
        <Binding>Electronics</Binding>
        <Brand>Panasonic</Brand>
        <CatalogNumberList>
          <CatalogNumberListElement>TYER3D4M</CatalogNumberListElement>
          <CatalogNumberListElement>TYER3D4MU</CatalogNumberListElement>
          <CatalogNumberListElement>TY-ER3D4MU</CatalogNumberListElement>
        </CatalogNumberList>
        <Color>One Color</Color>
        <Department>Electronics</Department>
        <EAN>0885170075207</EAN>
        <EANList>
          <EANListElement>0885170075207</EANListElement>
        </EANList>
        <Feature>Lightweight Active Shutter 3D Eyewear</Feature>
        <Feature>USB Rechargeable</Feature>
        <Feature>RF Compatible</Feature>
        <IsAutographed>0</IsAutographed>
        <IsMemorabilia>0</IsMemorabilia>
        <ItemDimensions>
          <Height Units="hundredths-inches">170</Height>
          <Length Units="hundredths-inches">340</Length>
          <Weight Units="hundredths-pounds">10</Weight>
          <Width Units="hundredths-inches">670</Width>
        </ItemDimensions>
        <Label>Panasonic</Label>
        <ListPrice>
          <Amount>7995</Amount>
          <CurrencyCode>USD</CurrencyCode>
          <FormattedPrice>$79.95</FormattedPrice>
        </ListPrice>
        <Manufacturer>Panasonic</Manufacturer>
        <Model>TY-ER3D4MU</Model>
        <MPN>TY-ER3D4MU</MPN>
        <NumberOfItems>1</NumberOfItems>
        <PackageDimensions>
          <Height Units="hundredths-inches">240</Height>
          <Length Units="hundredths-inches">690</Length>
          <Weight Units="hundredths-pounds">30</Weight>
          <Width Units="hundredths-inches">350</Width>
        </PackageDimensions>
        <PackageQuantity>1</PackageQuantity>
        <PartNumber>TY-ER3D4MU</PartNumber>
        <ProductGroup>CE</ProductGroup>
        <ProductTypeName>CONSUMER_ELECTRONICS</ProductTypeName>
        <Publisher>Panasonic</Publisher>
        <Size>One Size</Size>
        <SKU>292782</SKU>
        <Studio>Panasonic</Studio>
        <Title>Panasonic VIERA TY-ER3D4MU Active Shutter 3D Eyewear</Title>
        <UPC>885170075207</UPC>
        <UPCList>
          <UPCListElement>885170075207</UPCListElement>
        </UPCList>
      </ItemAttributes>
      <OfferSummary>
        <LowestNewPrice>
          <Amount>5400</Amount>
          <CurrencyCode>USD</CurrencyCode>
          <FormattedPrice>$54.00</FormattedPrice>
        </LowestNewPrice>
        <LowestUsedPrice>
          <Amount>4294</Amount>
          <CurrencyCode>USD</CurrencyCode>
          <FormattedPrice>$42.94</FormattedPrice>
        </LowestUsedPrice>
        <TotalNew>24</TotalNew>
        <TotalUsed>18</TotalUsed>
        <TotalCollectible>0</TotalCollectible>
        <TotalRefurbished>0</TotalRefurbished>
      </OfferSummary>
      <Offers>
        <TotalOffers>1</TotalOffers>
        <TotalOfferPages>1</TotalOfferPages>
        <MoreOffersUrl>http://www.amazon.com/gp/offer-listing/B007EHI1DK%3FSubscriptionId%3DIY7F4M00OF6I7TRD3VAS%26tag%3Daztag-20%26linkCode%3Dxm2%26camp%3D2025%26creative%3D386001%26creativeASIN%3DB007EHI1DK</MoreOffersUrl>
        <Offer>
          <OfferAttributes>
            <Condition>New</Condition>
          </OfferAttributes>
          <OfferListing>
            <OfferListingId>rkyW%2Bed7Qb8t28tJRRHkKizuk2CxNF4SI6W9XAnbXI8JX%2FJNpUY%2B8zqnnNRe3Vt2l%2B8rUMqypquQnAE66PYmf32dJeor6DifXvXKscwOqyrLwgFZORqmDg%3D%3D</OfferListingId>
            <Price>
              <Amount>5851</Amount>
              <CurrencyCode>USD</CurrencyCode>
              <FormattedPrice>$58.51</FormattedPrice>
            </Price>
            <AmountSaved>
              <Amount>2144</Amount>
              <CurrencyCode>USD</CurrencyCode>
              <FormattedPrice>$21.44</FormattedPrice>
            </AmountSaved>
            <PercentageSaved>27</PercentageSaved>
            <Availability>Usually ships in 24 hours</Availability>
            <AvailabilityAttributes>
              <AvailabilityType>now</AvailabilityType>
              <MinimumHours>0</MinimumHours>
              <MaximumHours>0</MaximumHours>
            </AvailabilityAttributes>
            <IsEligibleForSuperSaverShipping>1</IsEligibleForSuperSaverShipping>
          </OfferListing>
        </Offer>
      </Offers>
      <CustomerReviews>
        <IFrameURL>http://www.amazon.com/reviews/iframe?akid=AKIAIBT3ANF6TOEOKXVA&amp;alinkCode=xm2&amp;asin=B007EHI1DK&amp;atag=aztag-20&amp;exp=2013-01-05T05%3A23%3A21Z&amp;v=2&amp;sig=yz1U1nT8mWjFGauK3umnsOqp9BTzWwGOAAiLCyZ%2BEPM%3D</IFrameURL>
        <HasReviews>true</HasReviews>
      </CustomerReviews>
      <EditorialReviews>
        <EditorialReview>
          <Source>Product Description</Source>
          <Content>&lt;strong&gt;3D Playback Type:&lt;/strong&gt; Active Shutter 3D Method&lt;br /&gt;&lt;strong&gt;Transmittance Method:&lt;/strong&gt; RF (Bluetooth)/ Full HD 3D Glasses Standard Compatible&lt;br /&gt;&lt;strong&gt;Battery Type: &lt;/strong&gt;Lithium-ion Polymer Rechargeable Battery&lt;br /&gt;&lt;strong&gt;Battery Duration:&lt;/strong&gt; Approximately 30 hours of operation for a 30-minute full battery charge (Approximately 3 hours of operation for a 2-minute battery charge)&lt;em&gt; *The battery duration will change as per the total usage time with the number of charge/discharge cycles &lt;/em&gt;&lt;br /&gt;&lt;strong&gt;Package Included:&lt;/strong&gt; 1 Pair of Eyewear &lt;br /&gt;Note: These glasses are only compatible with 2012 VIERA HDTVs&lt;br /&gt;&lt;br /&gt; &lt;div style="text-align: left;"&gt;&lt;strong&gt;Accessory Compatibility Chart&lt;br /&gt;&lt;/strong&gt;&lt;/div&gt; &lt;img height="375" src="http://g-ecx.images-amazon.com/images/G/01/electronics/Cat500/Panasonic/2012/accessory_compatibility_2._V138249826_.gif" width="650" /&gt;&lt;br /&gt;&lt;br /&gt;</Content>
          <IsLinkSuppressed>0</IsLinkSuppressed>
        </EditorialReview>
      </EditorialReviews>
      <SimilarProducts>
        <SimilarProduct>
          <ASIN>B007K9P7H0</ASIN>
          <Title>Samsung SSG-4100GB 3D Active Glasses 2012 Models - Black</Title>
        </SimilarProduct>
        <SimilarProduct>
          <ASIN>B00752VKSC</ASIN>
          <Title>Panasonic VIERA TC-P55ST50 55-Inch 1080p 600Hz Full HD 3D Plasma TV</Title>
        </SimilarProduct>
        <SimilarProduct>
          <ASIN>B00752R4PK</ASIN>
          <Title>Panasonic DMP-BDT220 Integrated Wi-Fi 3D Blu-ray DVD Player</Title>
        </SimilarProduct>
        <SimilarProduct>
          <ASIN>B00752VKFA</ASIN>
          <Title>Panasonic VIERA TC-P55GT50 55-Inch 1080p 600Hz Full HD 3D Plasma TV</Title>
        </SimilarProduct>
        <SimilarProduct>
          <ASIN>B00752VL8G</ASIN>
          <Title>Panasonic VIERA TC-P60GT50 60-Inch 1080p 600Hz Full HD 3D Plasma TV</Title>
        </SimilarProduct>
      </SimilarProducts>
      <BrowseNodes>
        <BrowseNode>
          <BrowseNodeId>3224438011</BrowseNodeId>
          <Name>3D Glasses</Name>
          <Ancestors>
            <BrowseNode>
              <BrowseNodeId>172532</BrowseNodeId>
              <Name>Audio &amp; Video Accessories</Name>
              <Ancestors>
                <BrowseNode>
                  <BrowseNodeId>281407</BrowseNodeId>
                  <Name>Accessories &amp; Supplies</Name>
                  <Ancestors>
                    <BrowseNode>
                      <BrowseNodeId>493964</BrowseNodeId>
                      <Name>Categories</Name>
                      <IsCategoryRoot>1</IsCategoryRoot>
                      <Ancestors>
                        <BrowseNode>
                          <BrowseNodeId>172282</BrowseNodeId>
                          <Name>Electronics</Name>
                        </BrowseNode>
                      </Ancestors>
                    </BrowseNode>
                  </Ancestors>
                </BrowseNode>
              </Ancestors>
            </BrowseNode>
          </Ancestors>
        </BrowseNode>
        <BrowseNode>
          <BrowseNodeId>1288264011</BrowseNodeId>
          <Name>All product</Name>
          <Ancestors>
            <BrowseNode>
              <BrowseNodeId>1267878011</BrowseNodeId>
              <Name>Products</Name>
              <IsCategoryRoot>1</IsCategoryRoot>
              <Ancestors>
                <BrowseNode>
                  <BrowseNodeId>1267877011</BrowseNodeId>
                </BrowseNode>
              </Ancestors>
            </BrowseNode>
          </Ancestors>
        </BrowseNode>
        <BrowseNode>
          <BrowseNodeId>3545110011</BrowseNodeId>
          <Name>Home Entertainment</Name>
          <Children>
            <BrowseNode>
              <BrowseNodeId>3547652011</BrowseNodeId>
              <Name>Blu-Ray Players</Name>
            </BrowseNode>
            <BrowseNode>
              <BrowseNodeId>3547650011</BrowseNodeId>
              <Name>DVD Players</Name>
            </BrowseNode>
            <BrowseNode>
              <BrowseNodeId>6183878011</BrowseNodeId>
              <Name>Home Theater Projectors</Name>
            </BrowseNode>
            <BrowseNode>
              <BrowseNodeId>1294446011</BrowseNodeId>
              <Name>Televisions</Name>
            </BrowseNode>
            <BrowseNode>
              <BrowseNodeId>6183893011</BrowseNodeId>
              <Name>Television Tuners and Receivers</Name>
            </BrowseNode>
          </Children>
          <Ancestors>
            <BrowseNode>
              <BrowseNodeId>1294447011</BrowseNodeId>
              <Name>Electronics</Name>
              <Ancestors>
                <BrowseNode>
                  <BrowseNodeId>1267878011</BrowseNodeId>
                  <Name>Products</Name>
                  <IsCategoryRoot>1</IsCategoryRoot>
                  <Ancestors>
                    <BrowseNode>
                      <BrowseNodeId>1267877011</BrowseNodeId>
                    </BrowseNode>
                  </Ancestors>
                </BrowseNode>
              </Ancestors>
            </BrowseNode>
          </Ancestors>
        </BrowseNode>
        <BrowseNode>
          <BrowseNodeId>1293319011</BrowseNodeId>
          <Name>Electronics</Name>
          <Ancestors>
            <BrowseNode>
              <BrowseNodeId>1267879011</BrowseNodeId>
              <Name>Special Features</Name>
              <Ancestors>
                <BrowseNode>
                  <BrowseNodeId>1267877011</BrowseNodeId>
                </BrowseNode>
              </Ancestors>
            </BrowseNode>
          </Ancestors>
        </BrowseNode>
      </BrowseNodes>
    </Item>
  </Items>
</ItemLookupResponse>

I am trying to format this data into a CSV formated table using Javascript.

Can someone please help?

Thanks in advance! Praney

解决方案

After a long investigation i found out something that may help you.

Starting from the point that reinventing the wheel is such a stupid and time consuming task, i was looking for what other good programmers have already built out there on the internet.

Unfortunately I wasn't able to find out a direct converter form XML to CSV as the example you provide in PHP.

In my working example the XML have to pass from JSON first like this:

  • xml2json => json2csv

I took some pieces here and there and i will add the references of where i actually took all the code snippet i use for build the demo at the end of this answer. In this way you will be able to get a nice and clean documentation that will help you to improve this tool.

Here a simple demo:

function xmlTocsv() {

    var data = $("#xmlArea").val();

    var xml = "";

    if (data !== null && data.trim().length !== 0) {

        try {
            xml = $.parseXML(data);
        } catch (e) {
            throw e;
        }

        var x2js = new X2JS();

        data = x2js.xml2json(xml);
        jsonTocsvbyjson(data);
        
    }
}

function jsonTocsvbyjson(data, returnFlag) {

    arr = [];
    flag = true;

    var header = "";
    var content = "";
    var headFlag = true;

    try {

        var type1 = typeof data;

        if (type1 != "object") {
            data = processJSON($.parseJSON(data));
        } else {
            data = processJSON(data);
        }

    } catch (e) {
        if (returnFlag === undefined || !returnFlag) {
            console.error("Error in Convert to CSV");
        } else {
            console.error("Error in Convert :" + e);
        }
        return false;
    }

    $.each(data, function(k, value) {
        if (k % 2 === 0) {
            if (headFlag) {
                if (value != "end") {
                    header += value + ",";
                } else {
                    // remove last colon from string
                    header = header.substring(0, header.length - 1);
                    headFlag = false;
                }
            }
        } else {
            if (value != "end") {
                var temp = data[k - 1];
                if (header.search(temp) != -1) {
                    content += value + ",";
                }
            } else {
                // remove last colon from string
                content = content.substring(0, content.length - 1);
                content += "
";
            }
        }

    });

    if (returnFlag === undefined || !returnFlag) {
        $("#csvArea").val(header + "
" + content);
    } else {
        return (header + "
" + content);
    }
}

function processJSON(data) {

    $.each(data, function(k, data1) {

        var type1 = typeof data1;

        if (type1 == "object") {

            flag = false;
            processJSON(data1);
            arr.push("end");
            arr.push("end");

        } else {
            arr.push(k, data1);
        }

    });
    return arr;
}

<!DOCTYPE html>
<html>
<head>
<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js'></script>
<script type='text/javascript' src="https://cdn.rawgit.com/abdmob/x2js/master/xml2json.js"></script>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
    <h1>XML2CSV Demo</h1>
    <button id="convertToXmlBtn" onclick="xmlTocsv()">XML => CSV</button>
  
    <div>        
        <h4>XML:</h4>
        <textarea id="xmlArea" cols="55" rows="15"></textarea>
    </div>
    
    <div>
        <h4>CSV:</h4>
        <textarea id="csvArea" cols="55" rows="15"></textarea>
    </div>    
</body>
</html>

References:

  • XML TO CSV Converter
  • x2js - XML to JSON and vice versa for JavaScript

Utils:

  • Working Plunkr

这篇关于使用 Javascript 将 XML 转换为 CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Google apps script get range of bytes from binary file(谷歌应用程序脚本从二进制文件中获取字节范围)
Sending Multiple attachments with Google Script from Google Drive(使用 Google 脚本从 Google Drive 发送多个附件)
Distributing Google Apps Scripts for Sheets in your company network(在您的公司网络中分发适用于表格的 Google Apps 脚本)
Upload file to my google drive from anyone using javascript(使用 javascript 将文件从任何人上传到我的谷歌驱动器)
quot;Shared Drivequot; support in Google Apps Script(“共享驱动器Google Apps 脚本中的支持)
Angular 2+ HTTP POST and GDrive API. Resumable file upload with name(Angular 2+ HTTP POST 和 GDrive API.带名称的可恢复文件上传)