Stack Overflow 上有一些类似的主题,但我找不到任何真正解释如何做到这一点的主题。
我有一个 API 将数据返回为XML
. 我想将其转换JSON
为我将其存储在MongoDB
.
<cj-api>
<products total-matched="231746" records-returned="999" page-number="1">
<product>
<ad-id>10648829</ad-id>
<advertiser-id>2618386</advertiser-id>
<advertiser-name>Acne Jeans UK</advertiser-name>
<advertiser-category>New Arrivals</advertiser-category>
<buy-url>http://www.tkqlhce.com/click-7227532-10648829?url=http%3A%2F%2Fshop.acnestudios.com%2Fpop-cord-white.html&cjsku=30X133-151</buy-url>
<catalog-id>cjo:939</catalog-id>
<currency>EUR</currency>
<description>Pop Cord White.</description>
<image-url>http://c893323.r23.cf3.rackcdn.com/catalog/product/cache/25/thumbnail/300x300/9df78eab33525d08d6e5fb8d27136e95/3/0/30X133-151_A_57419.jpg</image-url>
<in-stock>true</in-stock>
<isbn/>
<manufacturer-name>Acne Studios</manufacturer-name>
<manufacturer-sku/>
<name>Pop Cord White</name>
<price>200.0</price>
<retail-price/>
<sale-price/>
<sku>30X133-151</sku>
<upc/>
</product>
<product>
<ad-id>10648829</ad-id>
<advertiser-id>2618386</advertiser-id>
<advertiser-name>Acne Jeans UK</advertiser-name>
<advertiser-category>Jeans</advertiser-category>
<buy-url>http://www.dpbolvw.net/click-7227532-10648829?url=http%3A%2F%2Fshop.acnestudios.com%2Fflex-black.html&cjsku=30H126-129</buy-url>
<catalog-id>cjo:939</catalog-id>
<currency>EUR</currency>
<description>Acne Flex Black jeans are narrow, tight fitting jeans with a comfortable mid rise waist.<ul>
<li>Worn in black blue wash</li>
<li>Classic five pocket styling</li>
<li>Zippered fly front closure</li>
<li>Secures at the waist with bachelor button</li>
<li>Acne embossed rivets</li>
</ul>.</description>
<image-url>http://c893323.r23.cf3.rackcdn.com/catalog/product/cache/25/thumbnail/300x300/9df78eab33525d08d6e5fb8d27136e95/3/0/30H126-129_A_18.jpg</image-url>
<in-stock>true</in-stock>
<isbn/>
<manufacturer-name>Acne Studios</manufacturer-name>
<manufacturer-sku/>
<name>Flex Black</name>
<price>170.0</price>
<retail-price/>
<sale-price/>
<sku>30H126-129</sku>
<upc/>
</product>
</products>
</cj-api>
(假设只有 2 个产品 - 实际上有 231,746 个!)
在 Node 中,我request
用来收集这个 XML 并将其存储在一个名为body
. 我正在使用libxmljs
,像这样:
var xmlDoc = libxmljs.parseXmlString(body);
var product = xmlDoc.get('//product'); <!-- very unsure whether I'm using this correctly
问题是我完全不知道如何处理这些数据,而libxmljs 文档在这方面确实没有帮助。我想做一些相当于 jQuery 的事情:
$('product').each(function(){
var obj = {
advertiser-name: $(this).find('advertiser-name'),
buy-url: $(this).find('buy-url'),
... etc etc etc
})
我如何使用libxmljs
/ 另一个库来做到这一点,以便我可以更轻松地处理数据?