javascript - 将 xml 解析为 javascript 中的字典或字典数组
问题描述
我正在使用 axios 从肥皂服务中获取文本/xml。如何将其转换为可以轻松读取值的内容?
这是 axios 部分:
axios.post('https://something.net?WSDL',
xmls,
{headers:
{
'Content-Type' : 'text/xml',
'Access-Control-Allow-Origin' : '*',
SOAPAction : ''}
})
.then(response => {
this.weather.single = response.data
})
我从中得到了一个 xml 字符串
<?xml version="1.0" encoding="UTF-8"?><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><soapenv:Body><getCurrWeatherResponse xmlns="http://service"><getCurrWeatherReturn><currWindSpeed>31</currWindSpeed><currTemp>-4</currTemp><currWindDir>north</currWindDir></getCurrWeatherReturn></getCurrWeatherResponse></soapenv:Body></soapenv:Envelope>
我也将不得不处理这些数组
解决方案
你可以使用xml2json
npm。这会将 XML 转换为 json
npm install xml2json
let xmlParser = require('xml2json');
axios.post('https://something.net?WSDL',
xmls,
{headers:
{
'Content-Type' : 'text/xml',
'Access-Control-Allow-Origin' : '*',
SOAPAction : ''}
})
.then(response => {
this.weather.single = xmlParser.toJson(response.data)
})
尝试这个。
在这里我得到了这个回应
{
"soapenv:Envelope": {
"xmlns:soapenv": "http://schemas.xmlsoap.org/soap/envelope/",
"xmlns:xsd": "http://www.w3.org/2001/XMLSchema",
"xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance",
"soapenv:Body": {
"getCurrWeatherResponse": {
"xmlns": "http://service",
"getCurrWeatherReturn": {
"currWindSpeed": "31",
"currTemp": "-4",
"currWindDir": "north"
}
}
}
}
}
推荐阅读
- rtf - 在 BIP RTF 模板表中,最后一行未按要求出现
- sql - 在查询结束时应用 IF 条件
- linux - XKB_DEFAULT_OPTIONS=grp:shift_caps_switch 具有两个以上的键盘布局
- git - GitHub,推送错误:远程端意外挂断
- django - 如何挂钩 django-allauth 信号?
- javascript - 在一页上有多个 mat-button-toggle-groups
- c# - 无法统一将简单列表转换为字符串
- express - Braintree 与 VueJS 和 Express 服务器的集成在 Heroku 上的 MerchantID 与 localhost 不同
- python - 在 Python 中从三角形到倒三角形
- php - PHP 分页功能有时会生成超出需要的页面[最后一页为空]。我该如何解决?