Javascript 如何使用 fetch api 获取 XML

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37693982/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 20:38:59  来源:igfitidea点击:

How to fetch XML with fetch api

javascriptxmlfetch-api

提问by Trip1

I'm trying to making a weather app that displays the weather and the temperature of many days of the week. I'm currently using openweathermap api for such task, the thing is that the information that I want (that is the date of the weather) only comes in xml format. Since I'm rebuilding it in ES6(ES2015) for academic reasons I wanted to also use the fetch api but since the fetch method parses it, it just delivers an error. so how can i fetch it or mby there is a better way to do it.

我正在尝试制作一个天气应用程序,显示一周中许多天的天气和温度。我目前正在使用 openweathermap api 执行此类任务,问题是我想要的信息(即天气日期)仅以 xml 格式提供。由于出于学术原因,我在 ES6(ES2015) 中重建它,我也想使用 fetch api,但由于 fetch 方法解析它,它只会传递一个错误。那么我如何才能获取它或 mby 有更好的方法来做到这一点。

let apis = {
    currentWeather: { //get user selected recomendation weather
        api:"http://api.openweathermap.org/data/2.5/forecast/daily?lat=",
        parameters: "&mode=xml&units=metric&cnt=6&APPID=/*api key*/",
        url: (lat, lon) => {
            return apis.currentWeather.api + lat + "&lon=" + lon +
                   apis.currentWeather.parameters
        }
    }
};
function getCurrentLoc() { 
    return new Promise((resolve, reject) =>  navigator.geolocation
                                             .getCurrentPosition(resolve, reject))
}
function getCurrentCity(location) {
    const lat = location.coords.latitude;
    const lon = location.coords.longitude;
    return fetch(apis.currentWeather.url(lat, lon))
    .then(response => response.json())
    .then(data => console.log(data))
}
getCurrentLoc()
.then( coords => getCurrentCity(coords))

回答by JukkaP

Using native DOMParser getCurrentCity(location) can be written:

使用原生 DOMParser getCurrentCity(location) 可以写成:

function getCurrentCity(location) {
    const lat = location.coords.latitude;
    const lon = location.coords.longitude;
    return fetch(apis.currentWeather.url(lat, lon))
        .then(response => response.text())
        .then(str => (new window.DOMParser()).parseFromString(str, "text/xml"))
        .then(data => console.log(data))
}

回答by Gilad Artzi

I guess the error is coming from this function: response => response.json()since the response is not a valid JSON object (it's XML).

我猜错误来自这个函数:response => response.json()因为响应不是有效的 JSON 对象(它是 XML)。

As far as I know, there is no native XML parser for fetch, but you can handle the response as text and use a third party tool to do the actual parsing, for example jQuery has a $.parseXML()function.

据我所知,没有针对 的原生 XML 解析器fetch,但您可以将响应作为文本处理并使用第三方工具进行实际解析,例如 jQuery 有一个$.parseXML()函数。

It will look something like:

它看起来像:

function getCurrentCity(location) {
    const lat = location.coords.latitude;
    const lon = location.coords.longitude;
    return fetch(apis.currentWeather.url(lat, lon))
        .then(response => response.text())
        .then(xmlString => $.parseXML(xmlString))
        .then(data => console.log(data))
}

回答by Tore Aurstad

It is possible to use the npm xml-js library and node-fetch to do this in Node.js, for those who want to test this out in the Node REPL.

对于那些想在 Node REPL 中进行测试的人,可以使用 npm xml-js 库和 node-fetch 在 Node.js 中执行此操作。

First off we install the two modules xml-js and node-fetch with:

首先,我们安装两个模块 xml-js 和 node-fetch :

npm install xml-js --save npm install node-fetch --save

npm install xml-js --save npm install node-fetch --save

to store these two packages into package.json. Now over to our problem at hand - how to work with XML data returned from an API.

将这两个包存储到 package.json 中。现在转到我们手头的问题 - 如何处理从 API 返回的 XML 数据。

Consider the following example fetching a particular weather station in Norway:

考虑以下获取挪威特定气象站的示例:

const fetch = require('node-fetch');
const convert = require('xml-js');
let dataAsJson = {};
fetch('http://eklima.met.no/metdata/MetDataService?invoke=getStationsProperties&stations=68050&username=').then(response => response.text()).then(str => {
    dataAsJson = JSON.parse(convert.xml2json(str));
}).then(() => {
    console.log(`Station id returned from the WS is: ${dataAsJson.elements[0].elements[0].elements[0].elements[0].elements[0].elements.filter(obj => { return obj.name == 'stnr'; })[0].elements[0].text} Expecting 68050 here!`);
});

We now have got a variable that is actually parsed into a JSON object from the XML data using convert's xml2json method and using JSON.parse. If we want to print out the object, we can use JSON.stringify to turn the JSON object into a string. The retrieval of the station id in this code just shows the need to scan through an object graph deep for a given key, since turning XML into Json gives often even deeper object graphs, since the wrapping XML elements are always at the top of the "XML object JSON-graph". There are some tips around deep searching object graphs that are deep to look for a key, like obj-traverse library on GitHub

我们现在得到了一个变量,该变量实际上使用 convert 的 xml2json 方法和 JSON.parse 从 XML 数据解析为 JSON 对象。如果我们想打印出对象,我们可以使用 JSON.stringify 将 JSON 对象转换为字符串。在这段代码中检索站 id 只是表明需要深入扫描给定键的对象图,因为将 XML 转换为 Json 通常会提供更深的对象图,因为包装的 XML 元素总是在“ XML 对象 JSON 图形”。有一些关于深度搜索对象图的技巧可以深入寻找一个关键,比如GitHub 上的 obj-traverse 库