2012-11-13 18 views
2

我使用XML序列化,用矩形但这是生产一些讨厌的XML ...XML序列化到子节点没有新对象

我的班级是这样的:

[Serializable] 
    public class myObject 
    { 
     public Rectangle Region { get; set; } 

     //Some other properties and methods... 
    } 

和给我这个当我序列化到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!

我希望我可以抑制SizeLocation性能上Rectangle,或者用背景变量和[XmlIgnore]像这样的东西来结束:

[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... 
    } 

希望给我喜欢的东西:

<myObject> 
     <Region> 
     <X>141</X> 
     <Y>93</Y> 
     <Width>137</Width> 
     <Height>15</Height> 
     </Region> 
     ... 
    </myObject> 

代码不太好,但XML会被人们编辑,所以它会很好地得到一些在那里工作...

任何ide可能会在“????”中发生什么?或另一种方式做到这一点?

我宁愿不要有实现我自己的Rectangle版本...

+5

如果您将数据序列化层与业务对象分开,则可以执行任何您喜欢的操作。创建自己的'RectangleDTO'对象,它具有诸如'X','Y','Width','Height'等属性,然后通过转换器运行DTO对象以将其更改为/从您的业务对象。 –

+3

我必须回应克里斯所说的话;如果你的域对象不是你想要序列化的形状,那么不要打乱序列化器 - 而是添加一个DTO层。 –

+0

为什么人们会手动编辑XML?编辑在那里。无论如何,你可以简单地创建暴露'Rectangle'字段的属性,并将它们序列化,而不是字段本身。如果你实现了ISerializable接口,你几乎可以做任何事情。但是,我不确定XMLSerializer是否使用它。 – LightStriker

回答

2

感谢您的意见家伙,我结束下去一种DTO路线 - 我实现我自己的结构 - XmlRectangle,持四个int值我需要用[Serializable]来装饰。我加了隐式转换运营商,所以我可以把它作为一个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 
} 

然后拿着它作为数据有一个Rectangle属性暴露它作为一个XmlRectangle到串行的类是这样的:

[XmlElement("Region",typeof(XmlRectangle))] 
public Rectangle Region { get; set; }