简体   繁体   中英

DateTime.Parse throwing a ArgumentNullException

I'm trying to read DateTime objects from XML and load them into a List of Reminder objects.

Datetime.Parse is throwing an Argument Null Exception with message :

String reference not set to an instance of a string.

Here's my code:

    private void loadReminders()
    {
        var xml = File.ReadAllText("Reminders.xml");
        XmlReader xmlReader = XmlReader.Create(new StringReader(xml));
        while (xmlReader.Read())
        {
            if (xmlReader.Name.Equals("Reminder") && (xmlReader.NodeType == XmlNodeType.Element))
            {
                Reminders.Add(new Reminder(DateTime.Parse(xmlReader.GetAttribute("Time")), xmlReader.GetAttribute("Title"), xmlReader.GetAttribute("Message")));
            }
        }
    }

I'm not quite sure why this exception is being thrown, as the DateTime string to parse is clearly stored in the XML File.

<Reminders>
  <Reminder>
    <Time>2013-7-30 23:24</Time>
   <Title>Random Reminder</Title>
   <Message>Random Message</Message>
  </Reminder>
</Reminders>

Any help would be much appreciated.

If you decide to change your code using Linq to XML, then you can use this code:

var listTimes = doc.Elements("Reminders").Elements("Reminder").Select(s => s.Element("Time"));

foreach (var item in listTimes)
{
    Console.Write(DateTime.Parse(item.Value, CultureInfo.InvariantCulture));
}

With you current code, you can use something like this:

XmlReader xmlReader = XmlReader.Create(new StringReader(xml));

while (xmlReader.Read())
{
    if (xmlReader.Name.Equals("Time") && (xmlReader.NodeType == XmlNodeType.Element))
    {
        Console.WriteLine(DateTime.Parse((string)xmlReader.ReadElementContentAs(typeof(string), null), CultureInfo.InvariantCulture));
    }                
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM