c# - 没有新对象的子节点的 XML 序列化

标签 c# .net xml-serialization

我正在使用带有矩形的 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>

讨厌!

我希望我可以抑制 Rectangle 上的 SizeLocation 属性,或者使用支持变量和 [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 将由人们编辑,所以最好能得到一些在那里工作的东西......

有什么想法可以放在“????”中吗?或者另一种方法?

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

最佳答案

感谢大家的评论,我结束了一种 DTO 路线 - 我实现了自己的结构 - XmlRectangle,包含我需要用 [Serializable]< 装饰的四个 int 值。我添加了隐式转换运算符,因此我可以将它用作 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; }

关于c# - 没有新对象的子节点的 XML 序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13362631/

相关文章:

c# - 将 LINQ 结果传递给函数

c# - 有没有一种优雅的方法来解析单词并在大写字母前添加空格

.net - Windows CE 中的多语言应用程序支持?

c# - 使用 Mud Blazor,我如何在页面底部获得一个持久抽屉?

c# - C# 中与 Java ReentrantLock 和 Condition 的最佳匹配?

c# - 使用SqlConnection.Open里面使用(){} block ?

c# - 建筑问题

java - 删除 xsi :type information from xml/json JAXB?

.net - XmlSerializer 和 IEnumerable : Serialization possible w/o parameterless constructor: Bug?

.net - 如何在 .NET 中序列化此 Xml(数组)