views:

201

answers:

3

When I serialize;

public class SpeedDial
{
    public string Value { get; set; }
    public string TextTR { get; set; }
    public string TextEN { get; set; }
    public string IconId { get; set; }
}

It results:

<SpeedDial>
    <Value>110</Value>
    <TextTR>Yangın</TextTR>
    <TextEN>Fire</TextEN>
    <IconId>39</IconId>
</SpeedDial>

But what I want is this:

  <speedDial>
    <value>110</value>
    <text>
      <TR>Yangın</TR>
      <EN>Fire</EN>
    </text>
    <iconId>39</iconId>
  </speedDial>

I want to learn the canonical way...

+1  A: 

I won't do it if I were you, because you make your serializer dependent of your business objects. For lowercase you could use the xml-customattributes.

JSC
+2  A: 

Three approaches leap to mind:

1: create a property to use for the serialization, and hide the others with [XmlIgnore] 2: implement IXmlSerializable and do it yourself 3: create a separate DTO just for the serialization

Here's an example that re-factors the "text" portion into objects that XmlSerializer will like, while retaining the original public AIP:

[Serializable]
public class SpeedDial
{
    static void Main()
    {
        XmlSerializer ser = new XmlSerializer(typeof(SpeedDial));
        SpeedDial foo = new SpeedDial { Value = "110", TextTR = "Yangin",
            TextEN = "Fire", IconId = "39" };
        ser.Serialize(Console.Out, foo);
    }
    public SpeedDial()
    {
        Text = new SpeedDialText();
    }

    [XmlElement("text"), EditorBrowsable(EditorBrowsableState.Never)]
    public SpeedDialText Text { get; set; }

    public string Value { get; set; }
    [XmlIgnore]
    public string TextTR
    {
        get { return Text.Tr; }
        set { Text.Tr = value; }
    }
    [XmlIgnore]
    public string TextEN
    {
        get { return Text.En; }
        set { Text.En = value; }
    }

    public string IconId { get; set; }
}
[Serializable]
public class SpeedDialText
{
    [XmlElement("EN")]
    public string En { get; set; }
    [XmlElement("TR")]
    public string Tr { get; set; }
}
Marc Gravell
cool approach ;) tnx
erdogany
A: 
public class SpeedDial
{
    public string Value { get; set; }
    public TextClass text;
    public string IconId { get; set; }
}

public class TextClass
{
    public string TR { get; set; }
    public string EN { get; set; }
}