C# 从 URL 读取 xml
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14904171/
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
Read xml from URL
提问by locoss
This is what I have so far. I am trying to just read the XML from the URL and just get for example temperature, humidity....etc.... But every time I try something else it gives me an error. I want to retrieve the information and put it in a label.
这是我到目前为止。我正在尝试从 URL 中读取 XML 并获取例如温度、湿度......等......但是每次我尝试其他东西时,它都会给我一个错误。我想检索信息并将其放入标签中。
namespace WindowsFormsApplication1 {
public partial class Form1: Form {
public Form1() {
InitializeComponent();
}
private void btnSubmit_Click(object sender, EventArgs e) {
String zip = txtZip.Text;
XmlDocument weatherURL = new XmlDocument();
weatherURL.Load("http://api.wunderground.com/api/"
your_key "/conditions/q/" + zip + ".xml");
foreach(XmlNode nodeselect in weatherURL.SelectNodes("response/current_observation"));
}
}
}
采纳答案by locoss
It took me a bit of trial and error but I've got it. In C# make sure you are using - using System.Xml;
我花了一些试验和错误,但我已经明白了。在 C# 中确保你正在使用 - using System.Xml;
Here is the code using wunderground API. In order for this to work make sure you sign up for a key other wise it will not work. Where is say this your_key that is where you put in your key. It should look like something like this. I used a button and three labels to display the information.
这是使用 wunderground API 的代码。为了使它起作用,请确保您注册了一个密钥,否则它将不起作用。在哪里说这个 your_key 就是你放入钥匙的地方。它应该看起来像这样。我使用了一个按钮和三个标签来显示信息。
namespace wfats2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
XmlDocument doc1 = new XmlDocument();
doc1.Load("http://api.wunderground.com/api/your_key/conditions/q/92135.xml");
XmlElement root = doc1.DocumentElement;
XmlNodeList nodes = root.SelectNodes("/response/current_observation");
foreach (XmlNode node in nodes)
{
string tempf = node["temp_f"].InnerText;
string tempc = node["temp_c"].InnerText;
string feels = node["feelslike_f"].InnerText;
label2.Text = tempf;
label4.Text = tempc;
label6.Text = feels;
}
}
}
}
When you press the button you will get the information displayed in the labels assign. I am still experimenting and you are able to have some sort of refresh every so often instead of pressing the button every time to get an update.
当您按下按钮时,您将获得显示在标签分配中的信息。我仍在试验中,您可以每隔一段时间进行某种刷新,而不是每次都按下按钮来获取更新。
回答by Buddy Wagner
First off yeah you need to give more information in your question but off hand I can see that you have "your_key" inside of your URL. You are probably needing to replace that with your API key for this to work.
首先是的,您需要在问题中提供更多信息,但我可以看到您的 URL 中有“your_key”。您可能需要将其替换为您的 API 密钥才能正常工作。