c# – 使用不同类的通用列表XML序列化

我有以下代码:

BaseContent.cs

public class BaseContent
{
   // Some auto properties
}

News.cs

public class News : BaseContent
{
   // Some more auto properties
}

Events.cs

public class Event : BaseContent
{
   // Some more auto properites
}

GenericResponse.cs

public class GenericResponse<T> 
{
  [XmlArray("Content")]
  [XmlArrayItem("NewsObject",typeof(News)]
  [XmlArrayItem("EventObject",typeof(Event)]
  public List<T> ContentItems { get; set; }
}

NewsResponse.cs

public class NewsResponse : GenericResponse<News> {}

EventResponse.cs

public class EventResponse : GenericResponse<Event> {}

你可以看到,我有一个基类BaseContent和从它派生的两个类.接下来我有一个通用响应类,因为xml文件的结构总是相同的,但是在某些属性中它们有所不同.

我以为我可以用[XmlArrayItem]指定用于特定类的名称.但是现在我得到错误:

System.InvalidOperationException: Unable to generate a temporary class (result=1).
error CS0012: The type ‘System.Object’ is defined in an assembly that is not referenced. You must add a reference to assembly ‘System.Runtime,Version=4.0.0.0,Culture=neutral,PublicKeyToken=b03f5f7f11d50a3a’.

我无法添加此引用,因为我正在使用Windows 8应用程序.

如果我注释掉其中一个[XmlArrayItem],它的工作效果很好.

任何人都有一个想法来解决这个问题?

更新
我不能使用DataContractSerializer,因为我必须使用XmlAttributes

解决方法

编辑:随意下载 demo project

您没有提供对象的所有属性,所以允许我添加一些 – 就像一个例子:

public class BaseContent
{
    [XmlAttribute("Name")]
    public string Name { get; set; }
}

[XmlType(TypeName = "EventObject")]
public class Event : BaseContent
{
    [XmlAttribute("EventId")]
    public int EventId { get; set; }
}

[XmlType(TypeName = "NewsObject")]
public class News : BaseContent
{
    [XmlAttribute("NewsId")]
    public int NewsId { get; set; }
}

GenericResponse.cs可以这样定义 – 不需要为数组项指定typeof:

public class GenericResponse<T>
{
    [XmlArray("Content")]
    public List<T> ContentItems { get; set; }

    public GenericResponse()
    {
        this.ContentItems = new List<T>();
    }
}

然后你有响应类:

public class EventResponse : GenericResponse<Event>
{
}

public class NewsResponse : GenericResponse<News>
{
}

示例1:序列化EventResponse对象

var response = new EventResponse
{
    ContentItems = new List<Event> 
    {
        new Event {
            EventId = 1,Name = "Event 1"
        },new Event {
            EventId = 2,Name = "Event 2"
        }
    }
};

string xml = XmlSerializer<EventResponse>.Serialize(response);

输出XML:

<?xml version="1.0" encoding="utf-8"?>
<EventResponse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <Content>
        <EventObject Name="Event 1" EventId="1" />
        <EventObject Name="Event 2" EventId="2" />
    </Content>
</EventResponse>

如果您尝试与NewsResponse相同,它将正常工作. BTW我使用我的generic XmlSerializer,点击链接了解更多.

XmlSerializer.cs:

/// <summary>
/// XML serializer helper class. Serializes and deserializes objects from/to XML
/// </summary>
/// <typeparam name="T">The type of the object to serialize/deserialize.
/// Must have a parameterless constructor and implement <see cref="Serializable"/></typeparam>
public class XmlSerializer<T> where T: class,new()
{
    /// <summary>
    /// Deserializes a XML string into an object
    /// Default encoding: <c>UTF8</c>
    /// </summary>
    /// <param name="xml">The XML string to deserialize</param>
    /// <returns>An object of type <c>T</c></returns>
    public static T Deserialize(string xml)
    {
        return Deserialize(xml,Encoding.UTF8,null);
    }

    /// <summary>
    /// Deserializes a XML string into an object
    /// Default encoding: <c>UTF8</c>
    /// </summary>
    /// <param name="xml">The XML string to deserialize</param>
    /// <param name="encoding">The encoding</param>
    /// <returns>An object of type <c>T</c></returns>
    public static T Deserialize(string xml,Encoding encoding)
    {
        return Deserialize(xml,encoding,null);
    }

    /// <summary>
    /// Deserializes a XML string into an object
    /// </summary>
    /// <param name="xml">The XML string to deserialize</param>
    /// <param name="settings">XML serialization settings. <see cref="System.Xml.XmlReaderSettings"/></param>
    /// <returns>An object of type <c>T</c></returns>
    public static T Deserialize(string xml,XmlReaderSettings settings)
    {
        return Deserialize(xml,settings);
    }

    /// <summary>
    /// Deserializes a XML string into an object
    /// </summary>
    /// <param name="xml">The XML string to deserialize</param>
    /// <param name="encoding">The encoding</param>
    /// <param name="settings">XML serialization settings. <see cref="System.Xml.XmlReaderSettings"/></param>
    /// <returns>An object of type <c>T</c></returns>
    public static T Deserialize(string xml,Encoding encoding,XmlReaderSettings settings)
    {
        if (string.IsNullOrEmpty(xml))
            throw new ArgumentException("XML cannot be null or empty","xml");

        XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));

        using (MemoryStream memoryStream = new MemoryStream(encoding.GetBytes(xml)))
        {
            using (XmlReader xmlReader = XmlReader.Create(memoryStream,settings))
            {
                return (T) xmlSerializer.Deserialize(xmlReader);
            }
        }
    }

    /// <summary>
    /// Deserializes a XML file.
    /// </summary>
    /// <param name="filename">The filename of the XML file to deserialize</param>
    /// <returns>An object of type <c>T</c></returns>
    public static T DeserializeFromFile(string filename)
    {
        return DeserializeFromFile(filename,new XmlReaderSettings());
    }

    /// <summary>
    /// Deserializes a XML file.
    /// </summary>
    /// <param name="filename">The filename of the XML file to deserialize</param>
    /// <param name="settings">XML serialization settings. <see cref="System.Xml.XmlReaderSettings"/></param>
    /// <returns>An object of type <c>T</c></returns>
    public static T DeserializeFromFile(string filename,XmlReaderSettings settings)
    {
        if (string.IsNullOrEmpty(filename))
            throw new ArgumentException("filename","XML filename cannot be null or empty");

        if (! File.Exists(filename))
            throw new FileNotFoundException("Cannot find XML file to deserialize",filename);

        // Create the stream writer with the specified encoding
        using (XmlReader reader = XmlReader.Create(filename,settings))
        {
            System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
            return (T) xmlSerializer.Deserialize(reader);
        }
    }

    /// <summary>
    /// Serialize an object
    /// </summary>
    /// <param name="source">The object to serialize</param>
    /// <returns>A XML string that represents the object to be serialized</returns>
    public static string Serialize(T source)
    {
        // indented XML by default
        return Serialize(source,null,GetIndentedSettings());
    }

    /// <summary>
    /// Serialize an object
    /// </summary>
    /// <param name="source">The object to serialize</param>
    /// <param name="namespaces">Namespaces to include in serialization</param>
    /// <returns>A XML string that represents the object to be serialized</returns>
    public static string Serialize(T source,XmlSerializerNamespaces namespaces)
    {
        // indented XML by default
        return Serialize(source,namespaces,GetIndentedSettings());
    }

    /// <summary>
    /// Serialize an object
    /// </summary>
    /// <param name="source">The object to serialize</param>
    /// <param name="settings">XML serialization settings. <see cref="System.Xml.XmlWriterSettings"/></param>
    /// <returns>A XML string that represents the object to be serialized</returns>
    public static string Serialize(T source,XmlWriterSettings settings)
    {
        return Serialize(source,settings);
    }

    /// <summary>
    /// Serialize an object
    /// </summary>
    /// <param name="source">The object to serialize</param>
    /// <param name="namespaces">Namespaces to include in serialization</param>
    /// <param name="settings">XML serialization settings. <see cref="System.Xml.XmlWriterSettings"/></param>
    /// <returns>A XML string that represents the object to be serialized</returns>
    public static string Serialize(T source,XmlSerializerNamespaces namespaces,XmlWriterSettings settings)
    {
        if (source == null)
            throw new ArgumentNullException("source","Object to serialize cannot be null");

        string xml = null;
        XmlSerializer serializer = new XmlSerializer(source.GetType());

        using (MemoryStream memoryStream = new MemoryStream())
        {
            using (XmlWriter xmlWriter = XmlWriter.Create(memoryStream,settings))
            {
                System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(typeof(T));
                x.Serialize(xmlWriter,source,namespaces);

                memoryStream.Position = 0; // rewind the stream before reading back.
                using (StreamReader sr = new StreamReader(memoryStream))
                {
                    xml = sr.ReadToEnd();
                } 
            }
        }

        return xml;
    }

    /// <summary>
    /// Serialize an object to a XML file
    /// </summary>
    /// <param name="source">The object to serialize</param>
    /// <param name="filename">The file to generate</param>
    public static void SerializeToFile(T source,string filename)
    {
        // indented XML by default
        SerializeToFile(source,filename,GetIndentedSettings());
    }

    /// <summary>
    /// Serialize an object to a XML file
    /// </summary>
    /// <param name="source">The object to serialize</param>
    /// <param name="filename">The file to generate</param>
    /// <param name="namespaces">Namespaces to include in serialization</param>
    public static void SerializeToFile(T source,string filename,XmlSerializerNamespaces namespaces)
    {
        // indented XML by default
        SerializeToFile(source,GetIndentedSettings());
    }

    /// <summary>
    /// Serialize an object to a XML file
    /// </summary>
    /// <param name="source">The object to serialize</param>
    /// <param name="filename">The file to generate</param>
    /// <param name="settings">XML serialization settings. <see cref="System.Xml.XmlWriterSettings"/></param>
    public static void SerializeToFile(T source,XmlWriterSettings settings)
    {
         SerializeToFile(source,settings);
    }

    /// <summary>
    /// Serialize an object to a XML file
    /// </summary>
    /// <param name="source">The object to serialize</param>
    /// <param name="filename">The file to generate</param>
    /// <param name="namespaces">Namespaces to include in serialization</param>
    /// <param name="settings">XML serialization settings. <see cref="System.Xml.XmlWriterSettings"/></param>
    public static void SerializeToFile(T source,"Object to serialize cannot be null");

        XmlSerializer serializer = new XmlSerializer(source.GetType());

        using (XmlWriter xmlWriter = XmlWriter.Create(filename,settings))
        {
            System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(typeof(T));
            x.Serialize(xmlWriter,namespaces);
        }
    }

    #region Private methods


    private static XmlWriterSettings GetIndentedSettings()
    {
        XmlWriterSettings xmlWriterSettings = new XmlWriterSettings();
        xmlWriterSettings.Indent = true;
        xmlWriterSettings.IndentChars = "\t";

        return xmlWriterSettings;
    }

    #endregion
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


1:最直白的循环遍历方法,可以分为遍历key--value键值对以及所有的key两种表现形式2:用Linq的方式去查询(当然了这里要添加对应的命名空间 using System.Linq)如下为一个十分简单的代码示例:private void GetDicKeyByValue(){ Dicti...
private void ClearTextBox(){ foreach (var control in pnlDetail.Controls) { if (!(control is TextBox)) continue; var txtBox = (TextBox)control; txtBox.
原文叫看《墨攻》理解IOC概念 2006年多部贺岁大片以让人应接不暇的频率纷至沓来,其中张之亮的《墨攻》算是比较出彩的一部,讲述了战国时期墨家人革离帮助梁 国反抗赵国侵略的个人英雄主义故事,恢宏壮阔,浑雄凝重的历史场面相当震撼。其中有一个场景:当刘德华所饰的墨者革离到达梁国都城 下,城上梁国守军问:
System.Data.ConstraintException: Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints.
Request.Form value was detected from the client在使用ASP.NET MVC3 开发系统的用了百度的UEditor编辑器提交表单时遇到检测到有潜在危险的 Request.Form,我百度一下,试了网上的方法,都没用。要在Web.config增加&lt;h
右击文件夹-&gt;安全选项卡-&gt;添加-&gt;高级-&gt;立即查找Windows Server 2003:请您在目录添加IIS来宾帐号(IUSR_Hostname)的只读权限,以及Network Service组的读写修改权限。Windows Server 2000:请您在目录添加IIS来
&lt;compilationdebug=&quot;true&quot;&gt;&lt;buildProviders&gt;&lt;addextension=&quot;.html&quot;type=&quot;System.Web.Compilation.PageBuildProvider&q
在ASP.NET MVC 中 Spring.NET 配置注入的时候,下面这方式是可行的。&lt;spring&gt; &lt;context&gt; &lt;resource uri=&quot;config://spring/objects&quot; /&gt; &lt;/context&gt;
Stopwatch stopwatch = new Stopwatch();stopwatch.Start();。。。。。中间代码。。。&#x9;stopwatch.Stop();&#x9;long result = stopwatch.ElapsedMilliseconds;sqlBulkCopy.Close()
问题描述 在asp.net mvc 下配置ueditor图片上传时总是提示:缺少十六进制字符错误(IE下提示),起初还以为是我上传的图片名称中有中文字符所致,后来我又上传了英文字符名字的图片发现还是一样的错误提示:◆无赖之下只好到火狐下看错误的详情:◆第二个错误我无法解决,先看第一个,输入地址显示错
已经安装net2.0 和3.5 ,但IIS里面却只有1.1开始→运行→CMDC:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe -i按回车键后便会开始自动安装,安装完重启一下IIS在IIS中ASP.NET选项卡便可以看到。注
根据传进来不同的值,调用不同的方法View Code protected void btn_SwitchClick(object sender, EventArgs e){ string result = &quot;&quot;; switch (ddlMethod.SelectedValue)
整理两个 在C#中,用正则表达式 获取网页源代码标签的属性或值的方法 :1、获取标签中的值: CSDN 结果:CSDN/// /// 获取字符中指定标签的值 /// /// 字符串 /// 标签 /// 值 public static string GetTitleContent(string st
/// &lt;summary&gt;/// 集合装换DataTable/// &lt;/summary&gt;/// &lt;param name=&quot;list&quot;&gt;集合&lt;/param&gt;/// &lt;returns&gt;&lt;/returns&gt;publ
将目录下面所有的 .cs 文件合并到一个 code.cs 文件中,写著作权复制代码时的必备良药 @echo off echo 将该目录下所有.cs文件的内容合并到一个 code.cs 文件中! pause dir /ad/s/b &gt; folderPath.txt md codeTemp for
做接口开发的时候,往往接受参数或返回值是一个XML的字符串。如下图,不方便辨识 两种方法, 1.将它保存为xxx.xml,然后用浏览器打开。这种方法稍微有些麻烦。 2.使用 UltraEdit 工具
一个字段控制多个状态选项private void GenerateAdvice_OnClick(object sender, RoutedEventArgs e){ TestStatus c1 = TestStatus.A | TestStatus.C | TestStatus.E; v...
效果如下: 代码如下:
StartUp.cs public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseEndpoints(endpoints =&gt; { endpoints.MapControllerRoute(