首页 > 解决方案 > Windows 窗体:从网站到 dataGridView 的 XML

问题描述

我想将此XML的特定部分直接导入我在 Windows 窗体中的 dataGridView 中,而无需下载 XML 文件。

当前工作代码,正在下载完整文件(不需要):

var wd = new WebClient();
wd.DownloadFile("https://www.aviationweather.gov/adds/dataserver_current/current/metars.cache.xml", @"c:\temp\metars.xml");

var ds = new DataSet();
ds.ReadXml(@"c:\temp\metars.xml");

dataGridView1.DataSource = ds.Tables["METAR"];

有没有办法直接从链接获取 XML 的一部分,例如当 station_id=CYDL 时的 METAR 信息到 dataGridView?

标签: c#xmlwinformsdatagridviewwindows-forms-designer

解决方案


您可以通过流下载内容,而不是像这样保存到文件中:

using var client = new HttpClient();
using var contentStream = await client.GetStreamAsync("https://www.aviationweather.gov/adds/dataserver_current/current/metars.cache.xml");

var ds = new DataSet();
ds.ReadXml(contentStream);

dataGridView1.DataSource = ds.Tables["METAR"];

或者,如果您更喜欢非异步 ( await) 方式:

using var client = new HttpClient();
var streamTask = client.GetStreamAsync("https://www.aviationweather.gov/adds/dataserver_current/current/metars.cache.xml");
streamTask.Wait();
using var contentStream = streamTask.Result;

var ds = new DataSet();
ds.ReadXml(contentStream);

dataGridView1.DataSource = ds.Tables["METAR"];

推荐阅读