I’m a but frustrated. I’m playing around with xml-files. So this is my automatically created xml-File:
<Files>
<Lists>
<oList>
<Object>
<Name>test1</Name>
<DateCreated>2/11/2013 4:35:05 PM</DateCreated>
<DateDeadline>2/17/2013 12:00:00 AM</DateDeadline>
<Reward>none</Reward>
<Description>chocolate amedei 9</Description>
</Object>
</oList>
</Lists>
</Files>
The many start elements in the beginning have to be there because I want to extend the file later. So now I want to read this xml-file and create an object of a class (ThingsToDoObjects, it’s supposed to become a to-do-list some day) that needs exactly the parameters stored in the xml-file. This Object should be stored in a list. So this is what I have so far:
XmlDocument xmlListDoc = new XmlDocument();
xmlListDoc.Load(xmlFilePath);
foreach (XmlNode xnode in xmlListDoc.SelectNodes("Files/Lists/oList/Object"))
{
string n = xnode.SelectSingleNode("Name").InnerText.ToString();
DateTime c = Convert.ToDateTime(xnode.SelectSingleNode("DateCreated").InnerText.ToString());
DateTime d = Convert.ToDateTime(xnode.SelectSingleNode("DateDeadline").InnerText.ToString());
string r = xnode.SelectSingleNode("Reward").InnerText.ToString();
string de = xnode.SelectSingleNode("Description").InnerText.ToString();
ThingsToDoObjects NeuObject = new ThingsToDoObjects(n, c, d, r, de);
o.Add(NeuObject);
}
Now when I debug the following happens:
n is created fine, c is created fine. But d just doesn’t work.It gives an error:
“The string was not recognized as a valid DateTime”
(That’s my translation from German, so maybe the error might be called a bit different. What’s going on there? I hope I just made some stupid mistake.
By the way: I tried the ParseExactly() method but it dind’t work either and gave the same error.
Thanks in advance to everone who answers.
(I’m assuming you can’t change the XML format itself. It would be much better to use a standard format, as suggested by dtb.)
If you’ve got text in a known format, use
DateTime.ParseExactorDateTime.TryParseExact. They will work, if you give them the right format. I usually use the invariant culture for parsing in these cases too – you don’t want a user culture’s date separators etc to mess things up. In this case, it looks like the format string you want is"M/d/yyyy h:mm:ss tt".Sample code:
I’d also strongly suggest using LINQ to XML if you can. It’ll make your XML handling a lot simpler than your current code.