将类序列化为属性 [英] Serialize Class as attribute
问题描述
我有一个 Point 类,我想将其序列化为属性.这是我真正想要的示例:
I have a Point class which I want to serialize as attribute. Here is the example of what I really want:
public class PointXY
{
[XmlIgnore]
public Double X { get; set; }
[XmlIgnore]
public Double Y { get; set; }
public override string ToString()
{
return Points;
}
}
public class TestClass
{
[XmlAttribute]
public PointXY Points { get; set; }
}
测试类应该序列化为:
<TestClass Points="0.1 0.2">
</TestClass>
我知道如果使用 IXmlSerializable 接口实现 TestClass,这可以实现.但是我想要 PointsXY 应该将自己作为属性而不是元素发出.是否可以?如果是如何?这也应该被反序列化.
I know this can be achieved if TestClass is implemented using IXmlSerializable interface. But what I want PointsXY should emmit itself as attribute instead of element. Is it possible? If yes how? This should get deserialized as well.
推荐答案
我不知道有什么方法可以将整个类序列化为一个属性.
I don't know of a way to serialize an entire class as an attribute.
您要么必须实现 IXmlSerializable
,要么将属性添加到 TestClass
并将那个序列化为一个属性:
You're going to either have to implement IXmlSerializable
or add a property to TestClass
and serialize that as an attribute:
public class TestClass
{
[XmlIgnore]
public PointXY Points { get; set; }
[XmlAttribute("Points")]
public string PointString
{
get
{
return string.Format("{0} {1}",Points.X, Points.Y);
}
set
{
// TODO: Add null checking, validation, etc.
string[] parts = value.Split(' ');
Points = new PointXY {X = double.Parse(parts[0]), Y = double.Parse(parts[1])};
}
}
}
这篇关于将类序列化为属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!