c # синтаксический анализ дочерних узлов xml из строки для приложения погоды с использованием openweathermap.org и winforms - PullRequest
0 голосов
/ 28 января 2019

Я застрял на этом, и я уверен, что ответ прост.Я читаю XML-файл с URL и загружаю его.Я могу читать обычные элементы 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>

Вот код.Я хотел бы прочитать город lon и lat, а также восход и закат солнца.

private void button1_Click (отправитель объекта, EventArgs e) {string 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; }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...