Destroy multiple XML elements of the same name using the XmlSerializer class in C #

I have XML in the form

<BackupSchedule> <AggressiveMode>0</AggressiveMode> <ScheduleType>0</ScheduleType> <ScheduledDay>0</ScheduledDay> <ScheduledDay>1</ScheduledDay> <ScheduledDay>0</ScheduledDay> <ScheduledDay>0</ScheduledDay> <ScheduledDay>0</ScheduledDay> <ScheduledDay>0</ScheduledDay> <ScheduledDay>0</ScheduledDay> <WindowStart>480</WindowStart> <WindowEnd>1020</WindowEnd> <ScheduleInterval>0</ScheduleInterval> </BackupSchedule> 

I need to deserialize it, change its contents and save it back. I ran into a problem reading the ScheduledDay element. My class is like

 public class BackupScheduleSettings { public BackupScheduleSettings() { ScheduledDay = new int[7]; } ..... public int[] ScheduledDay { get; set; } ..... } 

Now, when I load XML content that has the correct values ​​for ScheduledDay, my array of classes is still NULL.

I cannot change the contents / format of the XML, as this is legacy code. I do not want to use XDocument to read the value, since it is a lot of XML, and I need to serialize it again.

I searched a lot without any help. Any ideas would be highly appreciated.

Thank...

+8
c # xml xml-serialization xml-deserialization
Mar 10 2018-11-12T00:
source share
3 answers

You do not want XmlArrayItem . You want the ints array to be serialized without a parent element, which means you have to decorate the XmlElement array itself. Since you have a specific order, you need to use the Order value for the XmlElement attribute. Here is the class modified accordingly:

 public class BackupScheduleSettings { public BackupScheduleSettings() { ScheduledDay = new int[7]; } [XmlElement(Order=1)] public int AggressiveMode; [XmlElement(Order=2)] public int ScheduleType; //[XmlArrayItem("ArrayWrapper")] [XmlElement(Order=3)] public int[] ScheduledDay { get; set; } [XmlElement(Order=4)] public int WindowStart; [XmlElement(Order=5)] public int WindowEnd; [XmlElement(Order=6)] public int ScheduleInterval; } 

Here is the generated xML:

 <BackupScheduleSettings> <AggressiveMode>0</AggressiveMode> <ScheduleType>0</ScheduleType> <ScheduledDay>0</ScheduledDay> <ScheduledDay>0</ScheduledDay> <ScheduledDay>0</ScheduledDay> <ScheduledDay>0</ScheduledDay> <ScheduledDay>0</ScheduledDay> <ScheduledDay>0</ScheduledDay> <ScheduledDay>0</ScheduledDay> <WindowStart>0</WindowStart> <WindowEnd>0</WindowEnd> <ScheduleInterval>0</ScheduleInterval> </BackupScheduleSettings> 
+15
Mar 10 '11 at 13:10
source share

Decorate your property:

 [XmlElement("ScheduledDay")] public int[] ScheduledDay { get; set; } 
+13
Mar 10 2018-11-11T00:
source share

To do this, you just need to do the following:

 [XmlElement] public int[] ScheduledDay { get; set; } 

By adding this attribute, every time a ScheduledDay is scanned by a serializer (de), it will know to add it to this array.

+1
Mar 10 2018-11-11T00:
source share



All Articles