AndreaNobili
AndreaNobili

Reputation: 42997

Some information about how to correctly extract DateTime from an XML document in C#?

I have the following situation.

In a C# program I initialize some object fields using the content of an XML file.

In the XML file I have the 2 followings date time fielnds:

<x:Published>May 21 2014</x:Published>
<x:LastUpdated>2014-05-21T17:00:38</x:LastUpdated>

As you can see these fields have different format.

To initialize the related object field in my code I found:

currentDeepSightVuln.Published = n_alertdocument.SelectSingleNode("./x:Published", nsmgr) == null ? DateTime.MinValue : DateTime.ParseExact(n_alertdocument.SelectSingleNode("./x:Published", nsmgr).InnerText, "MMM dd yyyy", System.Globalization.CultureInfo.InvariantCulture);

currentDeepSightVuln.LastUpdated = n_alertdocument.SelectSingleNode("./x:LastUpdated", nsmgr) == null ? DateTime.MinValue : XmlConvert.ToDateTime(n_alertdocument.SelectSingleNode("./x:LastUpdated", nsmgr).InnerText);

Is it right? Can I use the XmlConver.ToDateTime() method also for the firs XML data field? Why they used the ParseExact() and not XmlConvert.ToDateTime()

Tnx

Upvotes: 2

Views: 578

Answers (2)

Mike Dimmick
Mike Dimmick

Reputation: 9802

The XML Schema specification defines the representation expected for dates and times stored in an XML document. The XmlConvert.ToDateTime overloads which only take a single string are expecting to use this format. By using that method, rather than a variant of DateTime.Parse, you're saying you expect the interoperable format.

XmlConvert.ToDateTime does have overloads which take one or more format parameters to try, but those overloads are still a subset of the full string.

The Published date in your file does not conform to the XML Schema date data type, so it must be parsed with a method that can handle that format. DateTime.Parse can, XmlConvert.ToDateTime will reject it as an invalid format.

Upvotes: 1

Rik
Rik

Reputation: 29243

Yes, you should be able to use XmlConvert.ToDateTime by specifying the format string, as you're doing with DateTime.ParseExact:

XmlConvert.ToDateTime("May 21 2014", "MMM dd yyyy")

This method will end up calling DateTime.ParseExact, so it doesn't really matter which option you choose, as long as you're consistent.

For reference, here's the implementation of XmlConvert.ToDateTime(string, string[]):

public static DateTime ToDateTime(string s, string[] formats)
{
    return DateTime.ParseExact(s, formats, (IFormatProvider) DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AllowLeadingWhite | DateTimeStyles.AllowTrailingWhite);
}

Upvotes: 1

Related Questions