Reputation: 1
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.
Upvotes: 0
Views: 691
Reputation: 16900
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));
}
}
Upvotes: 1