Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple C# Xml Serialization

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;}
like image 979
GreyCloud Avatar asked Jul 15 '26 01:07

GreyCloud


2 Answers

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;}
}
like image 197
djdd87 Avatar answered Jul 17 '26 15:07

djdd87


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();
    }
}
like image 26
Codesleuth Avatar answered Jul 17 '26 13:07

Codesleuth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!