XmlSerializer-将属性成员序列化为属性
本文关键字:属性 序列化 成员 XmlSerializer- | 更新日期: 2023-09-27 17:51:14
我正在尝试将内部继承属性的所有成员序列化(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
的属性?
如果您将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" />