I have a class:
public class Car {
public string Model {get;set;}
public string SeatFinish {get;set;}
public string Audio {get;set;}
}
I want to use XML serialization attributes to serialize it to the following xml
<Car>
<Model>name</Model>
<Options>
<SeatFinish>Leather</SeatFinish>
<Audio>5 speaker</Audio>
</Options>
</Car>
For reasons specific to the project i cannot just create a property:
public List<string> Options;
Is there a way of specifying via attributes that a property is to be serialised under a certain xml Element (in this case an "Options" node)? Can I write a custom attribute that allows this? Any advice appreciated.
edit:
I see that having an options class will work but is there someway to acheive this without creating other classes? for example i might want to do this with only one property.
ideally i'd like to be able to specify
[Parent("Options")]
public string SeatFinish {get;set;}
Is this part of a domain model or similar? It sounds like you're going to want these options to be re-useable outside of the car object, so why not create a separate Options class?
public class Options
{
public string SeatFinish {get;set;}
public string Audio {get;set;}
}
And change your Car class to hold the Options class:
public class Car
{
public string Model {get;set;}
public Options Options {get;set;}
}
If possible, try changing the class to this:
public class Car {
public class CarOptions
{
public string SeatFinish { get; set; }
public string Audio { get; set; }
}
public string Model { get; set; }
public CarOptions Options { get; set; }
public Car()
{
this.Options = new CarOptions();
}
}
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