Solved

How do I accept MM/DD/YYYY date format in using XmlSerializer?

Posted on 2004-08-18
8
2,932 Views
Last Modified: 2008-01-09
Hello.

I am accepting an XML feed from a client. I have created a class for to match it and am attempting to use the XmlSerializer class to automatically convert the feed to a binary format for use. There is a date that is sent over in MM/DD/YYYY format and my call to XmlSerializer.Deserialize is giving me the following error:

String was not recognized as a valid DateTime.

Is there an XmlAttribute I can use to make the class accept this format, or something else I can do? I'm currently using [serial.XmlElementAttribute(DataType="date")], but that is working for MM/DD/YYYY. It is working if on some test cases in which I changed the format to YYYY-MM-DD, but that is not an option for me at this point unless I transform it which does not really make sense for one field.

Thanks,

Michael Mercieca
0
Comment
Question by:HydeNSeeka
  • 4
  • 3
8 Comments
 
LVL 14

Accepted Solution

by:
AvonWyss earned 400 total points
Comment Utility
The official XML date format is YYYY-MM-DD, and I don't know how you could tell the serializer to convert this as you need it. But why not store the date as as string in your binary object (which would allow for proper deserialization) and use a member method to convert it to a DateTime when needed?
0
 

Assisted Solution

by:Philyard8133
Philyard8133 earned 100 total points
Comment Utility
Hi,

I was curious because I'm just diving into Xml myself and so I did a little research and I think I was able to duplicate your problem. I found a blog entry that appeared to sum up your dilema (http://weblogs.asp.net/kaevans/archive/2003/05/07/6643.aspx)

W3C dictates that "the XML data type date requires the format YYYY-MM-DD." (w3schools.com)

I'm not sure how you are reading the xml in but depending on how flexible you can be you could define the field as a string type or else create a class that will read your prefered date format:


using System;
using System.Collections;
using System.IO;
using System.Xml.Serialization;

public class Group
{
      /* Set the element name and namespace of the XML element.
      By applying an XmlElementAttribute to an array,  you instruct
      the XmlSerializer to serialize the array as a series of XML
      elements, instead of a nested set of elements. */
      
      [XmlElement(ElementName = "MyDate")]
      public MyDate myDate;
 
}  

public class MyDate
{
       public DateTime dateValue;

      public MyDate()
      {
      }
      public MyDate(DateTime aValue)
      {
            dateValue = aValue;
      }
}

public class Run
{
      public static void Main()
      {
            Run test = new Run();
            test.SerializeObject("FirstDoc.xml");
            test.DeserializeObject("FirstDoc.xml");

            Console.ReadLine();
      }


      public void SerializeObject(string filename)
      {

            // Create the XmlSerializer.
            XmlSerializer s = new XmlSerializer(typeof(Group));

            // To write the file, a TextWriter is required.
            TextWriter writer = new StreamWriter(filename);

            /* Create an instance of the group to serialize, and set
               its properties. */
            Group group = new Group();
            
            group.myDate = new MyDate(DateTime.Today);
            
            // Serialize the object, and close the TextWriter.      
            s.Serialize(writer, group);
            writer.Close();
      }

      public void DeserializeObject(string filename)
      {
            FileStream fs = new FileStream(filename, FileMode.Open);
            XmlSerializer x = new XmlSerializer(typeof(Group));
            Group g = (Group) x.Deserialize(fs);
            Console.WriteLine(g.myDate.dateValue.ToShortDateString());
                        
      }
}


Hope that helps a little bit anyway!
-Philyard8133
0
 

Expert Comment

by:Philyard8133
Comment Utility

Sorry ! I posted the wrong MyDate class, that other one will just save it like a normal Xml date, oposite of what you wanted!

public class MyDate
{
      public string dateValue;

      public DateTime GetDateValue()
      {
            return Convert.ToDateTime(dateValue);
      }

      public MyDate()
      {
      }

      public MyDate(DateTime aValue)
      {
            dateValue = aValue.ToShortDateString();
      }
}
0
 
LVL 14

Expert Comment

by:AvonWyss
Comment Utility
Philyard8133, note that this is exactly what I was suggesting in my comment. ;-)
0
Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

 

Author Comment

by:HydeNSeeka
Comment Utility
Thanks guys. I was unaware of the "standard" date time format. I've given Avon 400 pts for the original answer and 100 to Philyard for taking the time to add all of the code. Your help is much appreciated.
0
 
LVL 14

Expert Comment

by:AvonWyss
Comment Utility
You're welcome, and thank you very much.
0
 

Expert Comment

by:Philyard8133
Comment Utility
Thank you HydeNSeeka!

AvonWyss - you were too quick for me! when I first check there were no comments and I didn't refresh before I posted mine :p
0
 
LVL 14

Expert Comment

by:AvonWyss
Comment Utility
Sorry Philyard8133, I must admit that you certainly needed more time to write your comment than I did. I hope you aren't too disappointed about that... I wish you all the best!
0

Featured Post

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

Article by: Ivo
C# And Nullable Types Since 2.0 C# has Nullable(T) Generic Structure. The idea behind is to allow value type objects to have null values just like reference types have. This concerns scenarios where not all data sources have values (like a databa…
Summary: Persistence is the capability of an application to store the state of objects and recover it when necessary. This article compares the two common types of serialization in aspects of data access, readability, and runtime cost. A ready-to…
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, Just open a new email message.  In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…
You have products, that come in variants and want to set different prices for them? Watch this micro tutorial that describes how to configure prices for Magento super attributes. Assigning simple products to configurable: We assigned simple products…

771 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now