我对此感到困惑,我相信答案很简单。
我正在从网址读取xml文件并加载它。我可以读取普通的xml元素,但得到System.NullReferenceException: 'Object reference not set to an instance of an object.' when I try to read a child node
。
这是xml ...
<current>
<city id="420001851" name="Birmingham">
<coord lon="-86.9" lat="33.25"/>
<country>US</country>
<sun rise="2019-01-28T12:45:39" set="2019-01-28T23:15:58"/>
</city>
<temperature value="34" min="30.2" max="37.94" unit="fahrenheit"/>
<humidity value="89" unit="%"/>
<pressure value="1016" unit="hPa"/>
<wind>
<speed value="4.7" name="Gentle Breeze"/>
<gusts/>
<direction value="170" code="S" name="South"/>
</wind>
<clouds value="1" name="clear sky"/>
<visibility value="16093"/>
<precipitation mode="no"/>
<weather number="701" value="mist" icon="50d"/>
<lastupdate value="2019-01-28T12:56:00"/>
</current>
这是代码。我想读隆隆和拉特市以及太阳升起和落日的景色。
private void button1_Click(对象发送者,EventArgs e) { 字符串weburl =“ http://api.openweathermap.org/data/2.5/weather?zip=35080&mode=xml&units=imperial&APPID=7404500f8658346124e897905e88e5d0”;
var xml = new WebClient().DownloadString(new Uri(weburl));
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
textBox1.Text = xml;
string szTemp = doc.DocumentElement.SelectSingleNode("temperature").Attributes["value"].Value;
double temp = double.Parse(szTemp);
label1.Text = temp.ToString("N0") + "°";
//label1.Text = temp;
string szCityLocation = doc.DocumentElement.SelectSingleNode("coor").Attributes["lon"].Value;
label2.Text = szCityLocation;
//label1.Text = temp;
string wIcon = doc.DocumentElement.SelectSingleNode("weather").Attributes["icon"].Value;
string wiconx = (wIcon);
textBox2.Text = wiconx.ToString();
pictureBox1.Image = new Bitmap(@"c:\\weatherIcons\\" + wiconx.ToString() + ".png");
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
[Serializable, XmlRoot("Current")]
public class Current
{
public City city { get; set; }
public Temperature temperature { get; set; }
}
[XmlRoot(ElementName = "city")]
public class City
{
[XmlAttribute("name")]
public string name { get; set; }
[XmlAttribute("id")]
public int id { get; set; }
public Coord coord { get; set; }
public string country { get; set; }
public Sun sun { get; set; }
}
[XmlRoot(ElementName = "coor")]
public class Coord
{
[XmlAttribute("lat")]
public double lat { get; set; }
[XmlAttribute("lon")]
public double lon { get; set; }
}
[XmlRoot(ElementName = "sun")]
public class Sun
{
[XmlAttribute("set")]
public DateTime set { get; set; }
[XmlAttribute("rise")]
public DateTime rise { get; set; }
}
[XmlRoot(ElementName = "temperature")]
public class Temperature
{
[XmlAttribute("value")]
public double value { get; set; }
[XmlAttribute("unit")]
public string unit { get; set; }
[XmlAttribute("max")]
public double max { get; set; }
[XmlAttribute("min")]
public double min { get; set; }
}