Reputation: 1123
I am using xml serialization, with rectangles but this is producing some nasty XML...
My class is something like this:
[Serializable]
public class myObject
{
public Rectangle Region { get; set; }
//Some other properties and methods...
}
and that give me this when i serialize it to XML:
<myObject>
<Region>
<Location>
<X>141</X>
<Y>93</Y>
</Location>
<Size>
<Width>137</Width>
<Height>15</Height>
</Size>
<X>141</X>
<Y>93</Y>
<Width>137</Width>
<Height>15</Height>
</Region>
...
</myObject>
Yuck!
I am hoping that I can either suppress the Size
and Location
properties on the Rectangle
, or perhaps use backing variables and [XmlIgnore]
to end up with something like this:
[Serializable]
public class myObject
{
[XmlElement("????")]
public int RegionX;
[XmlElement("????")]
public int RegionY;
[XmlElement("????")]
public int RegionHeight;
[XmlElement("????")]
public int RegionWidth;
[XmlIgnore]
public Rectangle Region {get { return new Rectangle(RegionX, RegionY, RegionWidth, RegionHeight);}
//Some other properties and methods...
}
hopefully giving me something like:
<myObject>
<Region>
<X>141</X>
<Y>93</Y>
<Width>137</Width>
<Height>15</Height>
</Region>
...
</myObject>
Not so good in the code, but the XML will be edited by people so it would be good to get something which works there...
Any ides what might go in the "????"? or another way of doing this?
I would prefer not to have to implement my own version of Rectangle
...
Upvotes: 3
Views: 2489
Reputation: 1123
Thanks for the comments guys, i ended going down a sort of DTO route - I implemented my own Struct - XmlRectangle
, holding the four int values i need decorated with [Serializable]
. I added implicit conversion operators so i could use it as a Rectangle
:
[Serializable]
public struct XmlRectangle
{
#endregion Public Properties
public int X {get; set; }
public int Y {get; set; }
public int Height { get; set; }
public int Width { get; set; }
#endregion Public Properties
#region Implicit Conversion Operators
public static implicit operator Rectangle(XmlRectangle xmlRectangle)
{
return new Rectangle(xmlRectangle.X, xmlRectangle.Y, xmlRectangle.Width, xmlRectangle.Height);
}
public static implicit operator XmlRectangle(Rectangle rectangle)
{
return result = new XmlRectangle(){ X = rectangle.X, Y = Rectangle.Y, Height = Rectangle.Height, width = Rectangle.Width };
}
#endregion Implicit Conversion Operators
}
Then the class which held it as data had a Rectangle
property exposing it as an XmlRectangle
to the serializer the like this:
[XmlElement("Region",typeof(XmlRectangle))]
public Rectangle Region { get; set; }
Upvotes: 2