背景使用教程

如何安装:

npm包下载链接

【安装命令】

npm i xml2js

【引用】

import xml2js from 'xml2js';

具体实践:

如果xml具体内容既包含数组,又包含字典,可以看下解析后的对比:

【原始xml数据】

<Result>
<Message>可以预定</Message>
<CreateOrderValidateKey></CreateOrderValidateKey>
<ResultCode>0</ResultCode>
<InventoryPrice>[{"date":"2024-05-10","price":37700,"quota":9,"promotionPrice":18850,"dayPriceDetailList":null}]</InventoryPrice>
<CurrencyCode></CurrencyCode>
</Result>

【解析为JSON后】

{
"Result": {
"Message": [
"可以预定"
],
"CreateOrderValidateKey": [
""
],
"ResultCode": [
"0"
],
"InventoryPrice": [
"[{"date":"2024-05-11","price":37700,"quota":3,"promotionPrice":18850,"dayPriceDetailList":null}]"
],
"CurrencyCode": [
""
]
}
}

【转换方法调用】

xml2js.parseString(res.data, (err, result) => {
let price_info = result.Result.InventoryPrice[0]

for (let i = 0; i < price_info.length; i++) {
let price = price_info[i].price
}
});

【Tips】

上面的转换方法里,有关于price参数的解析,这个其实无法解析成功的,因为InventoryPrice[0]的value其实是字符串,无法按照数组去解析,这里必须再转换一次,将字符串转为为JSON

xml2js.parseString(res.data, (err, result) => {
console.log(result)
let price_info = JSON.parse(result.Result.InventoryPrice[0]);

for (let i = 0; i < price_info.length; i++) {
let price = price_info[i].price
vm.total_price = vm.paid_price = vm.total_price + (price / 100)
}
});

限 时 特 惠: 本站每日持续更新海量各大内部创业教程,一年会员只需98元,全站资源免费下载 点击查看详情
站 长 微 信: lzxmw777

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注