1

My code :

  string today = "url";
        var xmldoc = new XmlDocument();
        xmldoc.Load(today);

        XmlNodeList xnList = xmldoc.SelectNodes("cityinfo");

        foreach (XmlNode xn in xnList)
        {
            PrayerTimes pt = new PrayerTimes();
            pt.day = xn.Attributes["day"].Value;
            prayertimes.Add(pt);
        }

        foreach (XmlNode v in xnList)
        {
            listBox1.Items.Add(v);
        }

My xml file:

<?xml version="1.0" encoding="utf-8"?>
<cityinfo ID="1425" countryID="14" cityNameTR="Bakü (Bakı)" cityNameEN="Baku (Baki)" cityStateTR="Azerbaycan Cumhuriyeti" cityStateEN="Central Division" arzDer="40" arzDak="26" arzYon="N" tulDer="49" tulDak="52" tulYon="E" STulDer="60" STulDak="0" STulYon="E" tchange="1" height="250" scale="6" summerStart="87" summerEnd="304" qiblaangle="207.15" magdeg="6.11">
  <prayertimes dayofyear="0" day="31" month="12">6:10   6:26    7:58    8:49    12:34   12:53   15:15   15:52   16:46   17:30   18:26   19:05   19:16   14:33   a   b   </prayertimes>
  <prayertimes dayofyear="1" day="1" month="1">6:11 6:26    7:58    8:49    12:34   12:53   15:16   15:53   16:47   17:30   18:26   19:06   19:17   14:34   a   b   </prayertimes>

ERROR :Object reference not set to an instance of an object.

Gilad Green
  • 36,708
  • 7
  • 61
  • 95
Tagi
  • 302
  • 4
  • 17

3 Answers3

0

cityinfo does not have an attribute called "day", thus you get a NullReferenceException.

xn.ChildNodes will give you all childnodes of your cityinfo node.

Gilad Green
  • 36,708
  • 7
  • 61
  • 95
c0delama
  • 663
  • 6
  • 9
0

I would prefer XDocument. You can access values and attributes like this:

XDocument doc = XDocument.Load(today); // XDocument.Load("url");
XElement cityinfo = doc.Element("cityinfo");
foreach (XElement el in cityinfo.Elements())
{
    PrayerTimes pt = new PrayerTimes();
    pt.day = el.Attribute(XName.Get("day")).Value;
    prayertimes.Add(pt);
}
c0d3b34n
  • 534
  • 7
  • 14
0
var xmldoc = new XmlDocument();
xmldoc.Load("url");

var xnlist = XElement.Parse(xmldoc.InnerXml);
foreach (var xn in xnlist.Elements())
{
    PrayerTimes pt = new PrayerTimes();
    pt.day = xn.Attribute("day").Value;
    prayertimes.Add(pt);
}

You can also use XML Linq to achieve this.