How to combine multiple properties into one tag using object serialization override
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; }
}
Result:
<SpeedDial>
<Value>110</Value>
<TextTR>Yangın</TextTR>
<TextEN>Fire</TextEN>
<IconId>39</IconId>
</SpeedDial>
But I want this:
<speedDial>
<value>110</value>
<text>
<TR>Yangın</TR>
<EN>Fire</EN>
</text>
<iconId>39</iconId>
</speedDial>
I want to know the canonical path ...
0
source to share
3 answers
Three approaches are striking:
1: create a property used for serialization and hide the rest with [XmlIgnore]
2: do it IXmlSerializable
and do it yourself 3: create a separate DTO just for serialization
Here's an example that re-forces the "text" snippet on objects XmlSerializer
to please, while keeping the original open 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; }
}
+2
source to share