首页 > 解决方案 > 将 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>

我也将不得不处理这些数组

标签: javascriptxmlvue.jsaxios

解决方案


你可以使用xml2jsonnpm。这会将 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"
    }
   }
  }
 }
}

推荐阅读