创建正确序列化/反序列化派生类型的 XmlSerializer

发布于 2024-11-05 20:08:28 字数 3673 浏览 5 评论 0原文

我正在尝试创建一个 XmlSerializer 来正确序列化和反序列化派生类型。请看下面的代码。非常感谢使用 XmlAttributeOverrides 和额外类型来创建正确的 XmlSerializer 并将 GetVehicleResponse 实例与 VehicleObject 序列化为“SUV”对象的任何帮助。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using InteractiveSoftworks.Framework.Xml;
using System.IO;

namespace DowncastTest
{
   [XmlType(Namespace="urn:Test/Service")]
   public class GetVehicleResponse
   {
      [XmlElement(IsNullable=true, Namespace="urn:Test")]
      public Vehicle VehicleObject;
   }

   [XmlType( Namespace = "urn:test" )]
   public class Vehicle
   {
      public string Model;
      public string Number { get; set; }
   }

   public class Car : Vehicle
   {
      public int Doors { get; set; }
   }

   public class SUV : Car
   {
      public int Engines { get; set; }
   }

   public class MotorCycle : Vehicle
   {
      public int Seats { get; set; }
   }

   public class SportsBike : MotorCycle
   {
      public int Mirrors { get; set; }
   }


   public class Program
   {
      static void Main( string[] args )
      {
         XmlAttributeOverrides overrides = new XmlAttributeOverrides();
         CreateAttributeOverrides( typeof( Car ), "urn:Test", overrides );
         CreateAttributeOverrides( typeof( SUV ), "urn:Test", overrides );
         CreateAttributeOverrides( typeof( MotorCycle ), "urn:Test", overrides );
         CreateAttributeOverrides( typeof( SportsBike ), "urn:Test", overrides );

         Type[] extraTypes = new Type[] { typeof( Car ), typeof( SUV ), typeof( MotorCycle ), typeof( SportsBike ) };

         XmlSerializer xs = new XmlSerializer( typeof( GetVehicleResponse ), overrides, extraTypes, new XmlRootAttribute() { ElementName = "GetVehicleResponse", Namespace = "urn:Test" }, "urn:Test" );

         MemoryStream ms = new MemoryStream();
         xs.Serialize( ms, new GetVehicleResponse() { VehicleObject = new SUV() { Number = "AP29", Model = "2011", Doors = 4, Engines = 2 } } );

         string s = Encoding.UTF8.GetString( ms.GetBuffer() );

         Console.WriteLine( s );

         Console.WriteLine( "Done..." );
         Console.ReadKey();
      }

      internal static void CreateAttributeOverrides( Type type, string projectNamespace, XmlAttributeOverrides overrides )
      {
         // redirect the type if no explicit XmlAttributeType namespace has been provided
         //
         XmlAttributes typeAttributes = new XmlAttributes( type );
         XmlTypeAttribute typeAttribute = null;

         if ( typeAttributes.XmlType != null ) // inherit existing methodType attributes if any
         {
            if ( string.IsNullOrEmpty(typeAttributes.XmlType.Namespace) ) // only set the namespace if it isn't already defined
            {
               typeAttribute = typeAttributes.XmlType;
               typeAttribute.Namespace = projectNamespace;
            }
         }
         else
         {
            string rootNamespace = string.Empty;

            // if type defined Xml Root Attributes then get the namespace and add to type attributes
            //
            if ( typeAttributes.XmlRoot != null )
               rootNamespace = typeAttributes.XmlRoot.Namespace;

            if ( string.IsNullOrEmpty( rootNamespace ) )
               rootNamespace = projectNamespace;

            typeAttribute = new XmlTypeAttribute() { Namespace = rootNamespace };

         }

         if ( typeAttribute != null )
            overrides.Add( type, new XmlAttributes() { XmlType = typeAttribute } );  // use a fresh XmlAttributes as we only want to globally override XmlTypeAttribute
      }

   }
}

I'm trying to create an XmlSerializer that serialize and deserializes derived types properly. Please take a look at the code below. Any assistance in using XmlAttributeOverrides ad extra types to create proper XmlSerializer and serialize an instance of GetVehicleResponse with VehicleObject as "SUV" object is greatly appreciated.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using InteractiveSoftworks.Framework.Xml;
using System.IO;

namespace DowncastTest
{
   [XmlType(Namespace="urn:Test/Service")]
   public class GetVehicleResponse
   {
      [XmlElement(IsNullable=true, Namespace="urn:Test")]
      public Vehicle VehicleObject;
   }

   [XmlType( Namespace = "urn:test" )]
   public class Vehicle
   {
      public string Model;
      public string Number { get; set; }
   }

   public class Car : Vehicle
   {
      public int Doors { get; set; }
   }

   public class SUV : Car
   {
      public int Engines { get; set; }
   }

   public class MotorCycle : Vehicle
   {
      public int Seats { get; set; }
   }

   public class SportsBike : MotorCycle
   {
      public int Mirrors { get; set; }
   }


   public class Program
   {
      static void Main( string[] args )
      {
         XmlAttributeOverrides overrides = new XmlAttributeOverrides();
         CreateAttributeOverrides( typeof( Car ), "urn:Test", overrides );
         CreateAttributeOverrides( typeof( SUV ), "urn:Test", overrides );
         CreateAttributeOverrides( typeof( MotorCycle ), "urn:Test", overrides );
         CreateAttributeOverrides( typeof( SportsBike ), "urn:Test", overrides );

         Type[] extraTypes = new Type[] { typeof( Car ), typeof( SUV ), typeof( MotorCycle ), typeof( SportsBike ) };

         XmlSerializer xs = new XmlSerializer( typeof( GetVehicleResponse ), overrides, extraTypes, new XmlRootAttribute() { ElementName = "GetVehicleResponse", Namespace = "urn:Test" }, "urn:Test" );

         MemoryStream ms = new MemoryStream();
         xs.Serialize( ms, new GetVehicleResponse() { VehicleObject = new SUV() { Number = "AP29", Model = "2011", Doors = 4, Engines = 2 } } );

         string s = Encoding.UTF8.GetString( ms.GetBuffer() );

         Console.WriteLine( s );

         Console.WriteLine( "Done..." );
         Console.ReadKey();
      }

      internal static void CreateAttributeOverrides( Type type, string projectNamespace, XmlAttributeOverrides overrides )
      {
         // redirect the type if no explicit XmlAttributeType namespace has been provided
         //
         XmlAttributes typeAttributes = new XmlAttributes( type );
         XmlTypeAttribute typeAttribute = null;

         if ( typeAttributes.XmlType != null ) // inherit existing methodType attributes if any
         {
            if ( string.IsNullOrEmpty(typeAttributes.XmlType.Namespace) ) // only set the namespace if it isn't already defined
            {
               typeAttribute = typeAttributes.XmlType;
               typeAttribute.Namespace = projectNamespace;
            }
         }
         else
         {
            string rootNamespace = string.Empty;

            // if type defined Xml Root Attributes then get the namespace and add to type attributes
            //
            if ( typeAttributes.XmlRoot != null )
               rootNamespace = typeAttributes.XmlRoot.Namespace;

            if ( string.IsNullOrEmpty( rootNamespace ) )
               rootNamespace = projectNamespace;

            typeAttribute = new XmlTypeAttribute() { Namespace = rootNamespace };

         }

         if ( typeAttribute != null )
            overrides.Add( type, new XmlAttributes() { XmlType = typeAttribute } );  // use a fresh XmlAttributes as we only want to globally override XmlTypeAttribute
      }

   }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

只是在用心讲痛 2024-11-12 20:08:28

我认为您正在寻找 XmlIncludeAttribute

I think you are looking for the XmlIncludeAttribute

夏末 2024-11-12 20:08:28

作为替代方法,您可以使用支持额外的 XmlSerializer 形式可用于指定派生类型的 types 参数: 来自文档:

您还可以使用 extraTypes 参数来指定从基类派生的类型。

根据我的经验,这种方法效果很好,但并不适合所有情况,因为您需要准备好解决 Microsoft 实施中的潜在问题。请参阅 XmlSerializer 文档

As an alternative approach, you can use a form of the XmlSerializer that supports an extra types parameter that you can use to specify derived types: From the doc:

You can also use the extraTypes parameter to specify types derived from a base class.

This works fine in my experience, but is not perfect for every situation since you need to be prepared to address potential issues in Microsoft's implementation. See the section on Dynamically Generated Assemblies in the XmlSerializer doc for details.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文