如何强制XmlSerializer将元素序列化为编译类型的属性?

时间:2013-10-17 23:30:45

标签: c# .net xml serialization runtime

我已经提供了一些类似于此的预定义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>

我的目标是使用List<System.Windows.Point>实例将其反序列化为XmlSerializer,反之亦然。因此我定义了如下类型:

[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大约五次。它期望有一个支持列表,每个调用具有相同的引用,并且永远不为null。为了满足这些要求,这对我来说不是解决方案,因为我需要将List<CustomSerializedPoints>保留在内存中,只是为了使用属性而不是元素来编写点。

那么有人有一个更实用的解决方案吗?

另外我的XmlSerializer代码:

/* ... */
var serializer = new XmlSerializer(typeof(RootClass));
TextReader textReader = new StreamReader("file.xml");
(RootClass)serializer.Deserialize(textReader);
/* ... */

1 个答案:

答案 0 :(得分:4)

您可以通过在运行时更改其序列化属性来更改类的序列化/反序列化方式。 XmlAttributeOverrides类提供了这种可能性。以下示例代码正确地解析了您提供的XML:

XmlAttributes xa = new XmlAttributes();
XmlAttributes ya = new XmlAttributes();

xa.XmlAttribute = new XmlAttributeAttribute("X");
ya.XmlAttribute = new XmlAttributeAttribute("Y");

XmlAttributeOverrides xao = new XmlAttributeOverrides();
xao.Add(typeof(System.Windows.Point), "X", xa);
xao.Add(typeof(System.Windows.Point), "Y", ya);

var serializer = new XmlSerializer(typeof(RootClass), xao);
TextReader textReader = new StreamReader("file.xml");

var result = (RootClass)serializer.Deserialize(textReader);