【问题标题】:XmlSerializer construction with same named extra types具有相同命名的额外类型的 XmlSerializer 构造
【发布时间】:2009-12-19 04:31:24
【问题描述】:

嘿,我在构造 XmlSerializer 时遇到了麻烦,其中额外类型包含具有相同名称(但唯一全名)的类型。下面是一个说明我的场景的示例。

我无法操作的外部程序集中的类型定义:

public static class Wheel
{
  public enum Status { Stopped, Spinning }
}

public static class Engine
{
  public enum Status { Idle, Full }
}

我已经编写并可以控制的类:

public class Car
{
  public Wheel.Status WheelStatus;
  public Engine.Status EngineStatus;

  public static string Serialize(Car car)
  {
    var xs = new XmlSerializer(typeof(Car), new[] {typeof(Wheel.Status),typeof(Engine.Status)});

    var output = new StringBuilder();
    using (var sw = new StringWriter(output))
      xs.Serialize(sw, car);

    return output.ToString();
  }
}

XmlSerializer 构造函数抛出带有消息的 System.InvalidOperationException

“反映类型‘Engine.Status’时出错”

此异常具有 System.InvalidOperationException 类型的 InnerException 并带有消息

“类型 'Wheel.Status' 和 'Engine.Status' 都使用来自命名空间 '' 的 XML 类型名称 'Status'。使用 XML 属性为该类型指定唯一的 XML 名称和/或命名空间。”

鉴于我无法更改枚举类型,我如何构造一个能够成功序列化 Car 的 XmlSerializer?

【问题讨论】:

    标签: c# .net xml-serialization


    【解决方案1】:

    我注意到的第一件事是Car.Status 不存在。你的意思是Engine.Status?

    无论如何,如果这些枚举类型的设计方式无法自动序列化,您将不得不手动对其进行序列化。

    【讨论】:

      【解决方案2】:

      您可以通过在每个类上实现 IXmlSerializable 接口来对其进行序列化,然后您将获得 3 个方法

      GetSchema()
      ReadXml()
      WriteXml()
      

      在 GetSchema 方法中简单地放入 return null; 并在 WriteXml() 方法中放入您在序列化对象时编写 xml 所需的代码,在 ReadXml() 方法中放入您需要从 xml 文件中读取并重新创建反序列化时的对象。

      【讨论】:

        【解决方案3】:

        尝试使用 XmlElement 属性:

        public class Car
        {
            [XmlElement("WheelStatus")]
            public Wheel.Status WheelStatus;
            [XmlElement("EngineStatus")]
            public Engine.Status EngineStatus;
        
            ...
        
        }
        

        更新:刚试过这个,在这种情况下似乎不起作用。

        【讨论】:

          【解决方案4】:

          您可以在变量“状态”正上方添加[XmlElement(Name = "WheelStatus")] 以避免该问题。

          这会强制将保存时的 xml 名称(以及加载时的预期名称)重命名为您在“名称”中输入的任何字符串。但这也将允许您保留变量名“status”

          【讨论】:

            猜你喜欢
            • 2010-09-07
            • 1970-01-01
            • 2012-01-25
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-12-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多