2

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.

Neil Knight
  • 47,437
  • 25
  • 129
  • 188
tomet
  • 2,416
  • 6
  • 30
  • 45
  • Have you tried using DateTime.TryParse() ? – PhonicUK Feb 11 '13 at 15:51
  • Can you post the exact content of the string `xnode.SelectSingleNode("DateDeadline").InnerText.ToString()`? – John Willemse Feb 11 '13 at 15:52
  • I'm also beginner with this language, so sorry for my little question, maybe you allready did it but, : did you try datetime.parse(xnode.SelectSingleNode("DateCreated").InnerText.ToString())? – provençal le breton Feb 11 '13 at 15:54
  • I didn't do parse yet, just exact parse. But what makes e wonder is that the same thing for for similar strings not the same. – tomet Feb 11 '13 at 15:58
  • The string xnode.SelectSingleNode("DateDeadline").InnerText.ToString() is what it says in the xml, 2/17/2013 12:00:00 AM. I know ToString() is not necessary there, it was just one of my frustrated attempts. – tomet Feb 11 '13 at 16:00

3 Answers3

4

(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.ParseExact or DateTime.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:

using System;
using System.Globalization;

class Test
{
    static void Main()
    {
        string text = "2/17/2013 12:00:00 AM";
        string format = "M/d/yyyy h:mm:ss tt";
        DateTime value = DateTime.ParseExact(text, format,
                                             CultureInfo.InvariantCulture,
                                             DateTimeStyles.None);
        Console.WriteLine(value);
    }
}

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Great, that works. Though I have some questions left: Why M/d/yyyy and not mm/dd/yyyy? And can you tell me why my Convert.ToDateTime()-idea worked for one, but not the other? _It worked well for c, not for d. I find that strange. – tomet Feb 11 '13 at 16:10
  • So that's the link that answers all the questions concerning this I guess: http://msdn.microsoft.com/en-us/library/az4se3k1.aspx. I really thank you for answering almost all of my few c# questions I've asked here so far. You really help me a lot, thank you for that. – tomet Feb 11 '13 at 16:19
  • @user1953145: It's more this: http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx - as for why `c` "worked" - it's probably because 2/11/2013 can be parsed as d/M/yyyy... whereas 2/17/2013 can't. – Jon Skeet Feb 11 '13 at 16:24
1

Since you mentioned translating from German, I'm going to assume that you're in Germany. You're probably trying to parse the date as "you". What I mean is that the date is being parsed using the German culture formatter (dd/mm/yyyy) and there is no 17th month to parse to.

Try using this instead:

Convert.ToDateTime(value, CultureInfo.InvariantCulture.DateTimeFormat);
gislikonrad
  • 3,401
  • 2
  • 22
  • 24
0

There is a standard way to format date/time values in XML:

<DateCreated>2013-11-02T04:35:05</DateCreated>

You can parse this format using the XmlConvert.ToDateTime Method:

DateTime result = XmlConvert.ToDateTime("2013-11-02T04:35:05",
                                        XmlDateTimeSerializationMode.Utc);

Or, better yet, have a look at LINQ-to-XML and use the XElement to DateTime Explicit Conversion:

DateTime result = (DateTime)obj.Element("DateCreated");
Community
  • 1
  • 1
dtb
  • 213,145
  • 36
  • 401
  • 431