【发布时间】:2013-10-17 23:30:44
【问题描述】:
我已经给出了一些与此类似的预定义 XML:
<?xml version="1.0" encoding="utf-8"?>
<Root xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Points>
<Point X="1.345" Y="7.45" />
<Point X="1.123" Y="5.564" />
<Point X="3.34" Y="2.5345" />
</Points>
<!-- and a bunch of other attributes and structures which are perfectly serialized and deserialized by the XmlSerializer -->
</Root>
我的目标是使用XmlSerializer 实例将其反序列化为List<System.Windows.Point>,反之亦然。因此我定义了如下类型:
[Serializable]
[XmlRoot("Root")]
public class RootClass
{
public List<System.Windows.Point> Points { get; set; }
/* and more properties */
}
我的问题是XmlSerializer 将框架属性解释为XmlElement。为此,它们只能按原样读取和写入,而不是作为所需的属性。
我想到的一个解决方案是定义一个自定义点类型,它为每个坐标属性定义XmlAttribtueAttribute。这个自定义点被映射到System.Windows.Point 结构。如下所示:
[XmlIgnore]
public List<Point> Points { get; set; }
[XmlArray("Points")]
[XmlArrayItem("Point")]
public List<CustomSerializedPoint> CustomSerializedPoints
{
get { return this.Points.ToCustomSerializedPointList(); }
set { this.Points = value.ToPointList(); }
}
但是对于这个解决方案,我注意到,setter 从未被调用,XmlSerializer 调用CustomSerializedPoints 的 getter 大约五次。它期望有一个后备列表,每个调用都有相同的引用,并且永远不会为空。为了满足该要求,这对我来说不是解决方案,因为我需要将 List<CustomSerializedPoints> 保留在内存中,只是为了使用属性而不是元素来写入点。
那么有人有更实用的解决方案吗?
另外还有我的XmlSerializer 代码:
/* ... */
var serializer = new XmlSerializer(typeof(RootClass));
TextReader textReader = new StreamReader("file.xml");
(RootClass)serializer.Deserialize(textReader);
/* ... */
【问题讨论】:
-
查看“XmlSerializer Class”,然后告诉我们您之后是否还有其他问题。
标签: c# .net xml serialization runtime