0

I receive xml file like this. I need to convert this xml to an object.

    <?xml version="1.0" encoding="utf-8" ?>
    <PrepaidBill>
      <AccountDetails FCName="" TariffName="" Area="1000" SLDG="5000" SLEB="5000" ToDate="12/31/2013" FromDate="12/1/2013" Address="1st Cross, 26th Main, 9th block, Jayanagar" MeterNumber="DCPLCMTRXXX80001" ConsumerName="Pravin Nidoni"/>
    </PrepaidBill>

How to deserialize it? I have created a class for XML like

namespace ConvertXMLtoObject
{
        [XmlRoot("PrepaidBill")]
        public class BOPrepaidBill
        {
            public AccountDetails AccountDetails { get; set; }
        }

        public class AccountDetails
        {
            [XmlAttribute("FCName")]
            public string FCName { get; set; }

            [XmlAttribute("TariffName")]
            public string TariffName { get; set; }

            [XmlAttribute("Area")]
            public int Area { get; set; }

            [XmlAttribute("SLDG")]
            public int SLDG { get; set; }

            [XmlAttribute("SLEB")]
            public int SLEB { get; set; }

            [XmlAttribute("ToDate")]
            public DateTime ToDate { get; set; }

            [XmlAttribute("FromDate")]
            public DateTime FromDate { get; set; }

            [XmlAttribute("Address")]
            public string Address { get; set; }

            [XmlAttribute("MeterNumber")]
            public string MeterNumber { get; set; }

            [XmlAttribute("ConsumerName")]
            public string ConsumerName { get; set; }

        }
    }
Ondrej Janacek
  • 12,486
  • 14
  • 59
  • 93
sandeep c
  • 51
  • 8
  • 2
    Well, first steps for *deserializing* this xml into C# object is reading about [xml serialization/deserialization](http://stackoverflow.com/questions/364253/how-to-deserialize-xml-document) and trying to write some code. I suggest you to start from these steps – Sergey Berezovskiy Dec 19 '13 at 10:34
  • possible duplicate of [How does one parse XML files?](http://stackoverflow.com/questions/55828/how-does-one-parse-xml-files) – Kami Dec 19 '13 at 10:37
  • 2
    @SergeyBerezovskiy well there is problem for parsing datetime – sandeep c Dec 19 '13 at 10:41

1 Answers1

1

XmlSerializer internally uses XmlConvert for converting strings to required types. XmlConvert.ToDateTime converts strings to dates, but it requires date to be in "yyyy-MM-ddTHH:mm:sszzzzzz" format or its subsets. So, there is no way for you to convert "12/31/2013" into DateTime with serializer. Workaround is manually parsing your date string:

[XmlIgnore]
public DateTime ToDate { get; set; }

[XmlAttribute("ToDate")]
public string ToDateString 
{
    get { return ToDate.ToString("MM/dd/yyyy"); }
    set { ToDate = DateTime.Parse(value); }
}

Alternative solution (if possible) - changing date format in your xml file to "2013-01-12".

Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459