Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserialize int arrays from XML file

i am writing a c# project and i am trying to deserialize an object that has a field of type int[] and i want to make the deserialization in another manner.

Say i have a class:

class Player
{
   public string Name;
   public int[] Spells;
}

And a xml file from which i deserialize an instance of class Player:

<Player>
  <Name>John</Name>
  <Spells>
    <int>1</int>
    <int>5</int>
    <int>9</int>
  </Spells>
</Player>

The thing is i don't want that the xml file to look like that , i want it to be more like this:

<Player>
  <Name>John</Name>
  <Spells>1 5 9</Spells>
</Player>

I am using XmlSerializer and it only deserialize the field Spells only when reading form first xml . I wonder if it is a way to deserialize a int array just like a simple field.

like image 560
Stefan Avatar asked Apr 18 '11 11:04

Stefan


2 Answers

One of the way could be creating another property that would take space delimited set for serialization purposes. For example,

class Player
{
   public string Name;

   [XmlIgnore]
   public int[] Spells;

   [XmlElement("Spells")
   public string SpellsString
   {
     get
     {
        // array to space delimited string
     }
     set
     {
       // string to array conversion
     }
   }
}
like image 141
VinayC Avatar answered Oct 02 '22 14:10

VinayC


class Player
{
   public string Name { get; set; }
   public string SpellData { get; set; }

   public int[] Spells() {
        return SpellData.Split(" ").select(n=>int.parse(n)).ToArray();
   };
}

Something like that will make your xml data look the way you want to, since on the string and not the function would be serialized. But why do you care what your xml looks like? The other xml is a lot cleaner.

like image 38
Sergei Golos Avatar answered Oct 02 '22 15:10

Sergei Golos