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.
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
}
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With