I need to deserialize the following XML:
<TIMEWINDOWS>
<NUMBER>10</NUMBER>
<NO0>
<FROM>22-11-2013 08:00:00</FROM>
<TO>22-11-2013 11:59:00</TO>
</NO0>
<NO1>
<FROM>22-11-2013 12:00:00</FROM>
<TO>22-11-2013 15:59:00</TO>
</NO1>
<NO2>
<FROM>23-11-2013 08:00:00</FROM>
<TO>23-11-2013 11:59:00</TO>
</NO2>
<NO3>
<FROM>23-11-2013 12:00:00</FROM>
<TO>23-11-2013 15:59:00</TO>
</NO3>
...
</TIMEWINDOWS>
The output that I require is a collection (list, array, whatever) of TimeWindow
objects, for example:
public class TimeWindow
{
public string From { get; set; }
public string To { get; set; }
}
Is there a standard way to handle the NO0
, NO1
, NO2
, ... elements?
I can always build my own parser, but I would much prefer to use a standard approach, such as System.Xml.Serialization.XmlSerializer
.
The format of this is quite crazy. Unfortunately this means you will need to parse the xml manually with
XDocument
orXmlDocument
. Lets use the former as it is easier:The way that I used for solving this problem of mine was saving them to .xml files and retrieved from the .xml file. Check the below code:
For loading you may use the below:
Then you may save your XML based on:
and Load it based on:
There is no standard way to handle elements with different names. Because your xml is not standard xml. All children of same type should have same names otherwise they considered as different elements. Additional information (like index of window) should be provided via attributes or elements of child, not via element name:
So, you should handle this manually, e.g. by filtering out
<NUMBER>
element and just enumerating all other elementsAlso consider to use
DateTime
properties in yourTimeWindow
class, because they hold dates.A possibility is to do the following:
And if you have this class and help class, you can simply do the following (in another class of course):
After this, you can access the (at present time "string"-formatted) data via
For me, this worked some days ago. But I just wrote it from my mind.
//EDIT
Sorry, I didn't realize that there are different numbers of "NOx"-Tags. This example here works only, id you know the exact amount of those tags.
You could use LINQ to XML. Something like...
You'd probably want to add some checking for nulls around the FROM and TO elements to ensure they are present in the data.