XmlSerializer - 将属性成员序列化为属性

时间:2014-03-21 07:40:51

标签: c# xml properties serializer

我正在尝试序列化(XmlSerializer)已包含属性的所有成员作为属性。

两个类:

public class Tree
{
    public Point Location { get; set; }
}

public class AppleTree : Tree
{
    [XmlAttribute]
    public int FruitCount { get; set; }
}

主程序:

AppleTree appleTree = new AppleTree
{
    Location = new Point(10, 20),
    FruitCount = 69
};
// Serialize ...

现在我明白了:

<?xml version="1.0"?>
<AppleTree FruitCount="69">
  <Location>
    <X>10</X>
    <Y>20</Y>
  </Location>
</AppleTree>

但我希望Location的所有成员都是AppleTree的属性。 就像那样:

<?xml version="1.0"?>
<AppleTree FruitCount="69" X="10" Y="20" />

我知道,我可以这样:

public class Tree
{
    [XmlIgnore]
    public Point Location { get; set; }
}

public class AppleTree : Tree
{
    [XmlAttribute]
    public int FruitCount { get; set; }

    [XmlAttribute]
    public int X
    {
        get { return Location.X; }
        set { Location = new Point(value, Location.Y); }
    }

    [XmlAttribute]
    public int Y
    {
        get { return Location.Y; }
        set { Location = new Point(Location.X, value); }
    }
}

但我不想拥有所有属性的副本(这只是一个简单的例子)。

还有另一种解决方案吗?也许属性为XmlSerializer

1 个答案:

答案 0 :(得分:3)

如果将X和Y作为属性引入基类,则会得到所需的行为:

public class Tree
{

    [XmlIgnore]
    public Point Location { get; set;}

    [XmlAttribute]
    public double X { 
        get { return Location.X;} 
        set { Location = new Point(value, Location.Y); }
    }

    [XmlAttribute]
    public double Y { 
        get { return Location.Y;} 
        set { Location = new Point(Location.X, value); }
    }
}

public class AppleTree : Tree
{
    [XmlAttribute]
    public int FruitCount { get; set; }
}

为我序列化如下:

  

<?xml version="1.0" encoding="utf-8"?>
  <AppleTree xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:xsd="http://www.w3.org/2001/XMLSchema"
     X="10"
     Y="20"
     FruitCount="69" />