读取Xml属性c#

时间:2016-07-07 12:18:55

标签: c# xml attributes

我的代码:

  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);
        }

我的xml文件:

<?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>
  

错误:对象引用未设置为对象的实例。

3 个答案:

答案 0 :(得分:0)

cityinfo没有名为“day”的属性,因此您获得了NullReferenceException

xn.ChildNodes将为您提供cityinfo节点的所有子节点。

答案 1 :(得分:0)

我更喜欢XDocument。您可以像这样访问值和属性:

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);
}

答案 2 :(得分: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);
}

您也可以使用XML Linq来实现这一目标。