我继承了一个c#类。我已经成功地“构建”了对象。但是我需要将对象序列化为XML。有什么简单的方法吗?

看起来类已经为序列化设置了,但我不确定如何获得XML表示。我的类定义是这样的:

[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.domain.com/test")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://www.domain.com/test", IsNullable = false)]
public partial class MyObject
{
  ...
}

以下是我认为我能做的,但它不起作用:

MyObject o = new MyObject();
// Set o properties
string xml = o.ToString();

如何获得该对象的XML表示形式?


当前回答

我将从本·格里普卡的回答开始:

public void Save(string FileName)
{
    using (var writer = new System.IO.StreamWriter(FileName))
    {
        var serializer = new XmlSerializer(this.GetType());
        serializer.Serialize(writer, this);
        writer.Flush();
    }
}

I used this code earlier. But reality showed that this solution is a bit problematic. Usually most of programmers just serialize setting on save and deserialize settings on load. This is an optimistic scenario. Once the serialization failed, because of some reason, the file is partly written, XML file is not complete and it is invalid. In consequence XML deserialization does not work and your application may crash on start. If the file is not huge, I suggest first serialize object to MemoryStream then write the stream to the File. This case is especially important if there is some complicated custom serialization. You can never test all cases.

public void Save(string fileName)
{
    //first serialize the object to memory stream,
    //in case of exception, the original file is not corrupted
    using (MemoryStream ms = new MemoryStream())
    {
        var writer = new System.IO.StreamWriter(ms);    
        var serializer = new XmlSerializer(this.GetType());
        serializer.Serialize(writer, this);
        writer.Flush();

        //if the serialization succeed, rewrite the file.
        File.WriteAllBytes(fileName, ms.ToArray());
    }
}

现实场景中的反序列化应该与损坏的序列化文件算在一起,它有时会发生。负载函数由Ben Gripka提供。

public static [ObjectType] Load(string fileName)
{
    using (var stream = System.IO.File.OpenRead(fileName))
    {
        var serializer = new XmlSerializer(typeof([ObjectType]));
        return serializer.Deserialize(stream) as [ObjectType];        
    }    
}

它可能会被一些复苏场景所包裹。它适用于设置文件或其他文件,可以删除的情况下出现问题。

public static [ObjectType] LoadWithRecovery(string fileName)
{
    try
    {
        return Load(fileName);
    }
    catch(Excetion)
    {
        File.Delete(fileName); //delete corrupted settings file
        return GetFactorySettings();
    }
}

其他回答

这里有一个关于如何做到这一点的很好的教程

基本上应该使用System.Xml.Serialization.XmlSerializer类来做到这一点。

我修改了我的返回一个字符串,而不是像下面这样使用一个ref变量。

public static string Serialize<T>(this T value)
{
    if (value == null)
    {
        return string.Empty;
    }
    try
    {
        var xmlserializer = new XmlSerializer(typeof(T));
        var stringWriter = new StringWriter();
        using (var writer = XmlWriter.Create(stringWriter))
        {
            xmlserializer.Serialize(writer, value);
            return stringWriter.ToString();
        }
    }
    catch (Exception ex)
    {
        throw new Exception("An error occurred", ex);
    }
}

它的用法是这样的:

var xmlString = obj.Serialize();

我有一个简单的方法来序列化一个对象到XML使用c#,它的工作很棒,它是高度可重用的。我知道这是一个较老的帖子,但我想发布这个帖子,因为有人可能会发现这对他们有帮助。

下面是我如何调用该方法:

var objectToSerialize = new MyObject();
var xmlString = objectToSerialize.ToXmlString();

下面是完成这项工作的类:

注意:由于这些是扩展方法,它们需要在静态类中。

using System.IO;
using System.Xml.Serialization;

public static class XmlTools
{
    public static string ToXmlString<T>(this T input)
    {
        using (var writer = new StringWriter())
        {
            input.ToXml(writer);
            return writer.ToString();
        }
    }

    private static void ToXml<T>(this T objectToSerialize, StringWriter writer)
    {
        new XmlSerializer(typeof(T)).Serialize(writer, objectToSerialize);
    }
}

下面是一个通用的对象序列化器:

using System.IO;
using System.Text;
using System.Xml.Schema;

namespace System.Xml.Serialization
{
    /// <summary>
    /// Serializes and deserializes <typeparamref name="T"/> objects into XML documents.
    /// Allows you to control the process of encoding objects in XML.
    /// </summary>
    /// <typeparam name="T">Object type.</typeparam>
    public static class XmlSerializer<T>
    {
        private static readonly XmlSerializer _serializer = new XmlSerializer(typeof(T));
        private static readonly XmlWriterSettings _defaultWriterSettings = new XmlWriterSettings
        {
            CheckCharacters = false
            CloseOutput=false
            ConformanceLevel = ConformanceLevel.Auto,
            Encoding = Encoding.UTF8,
            indent=true,
            IndentChars = "\t",
            NamespaceHandling = NamespaceHandling.OmitDuplicates,
            NewLineChars = "\r\n",
            NewLineHandling = NewLineHandling.Replace,
            NewLineOnAttributes = false,
            OmitXmlDeclaration = false
        };
        private static readonly XmlReaderSettings _defaultReaderSettings = new XmlReaderSettings
        {
            CheckCharacters = false
            CloseInput=false
            ConformanceLevel = ConformanceLevel.Auto,
            DtdProcessing = DtdProcessing.Prohibit,
            IgnoreComments = true,
            IgnoreProcessingInstructions = true,
            IgnoreWhitespace=true,
            LineNumberOffset = 0
            LinePositionOffset = 0
            MaxCharactersFromEntities = 0,
            MaxCharactersInDocument = 0,
            NameTable = null
            // Schemas = null, // ???
            ValidationFlags = XmlSchemaValidationFlags.None,
            ValidationType = ValidationType. None,
            XmlResolver = null
        }; 
        
         /// <summary>
         /// Default character encoding.
         /// </summary>
         public static Encoding DefaultEncoding => Encoding.UTF8;

         /// <summary>
         /// Default settings for the <see cref="XmlWriter" /> instance being created.
         /// </summary>
         public static XmlWriterSettings DefaultXmlWriterSettings => _defaultWriterSettings.Clone();

         /// <summary>
         /// Default settings for the <see cref="XmlReader" /> instance that is created.
         /// </summary>
         public static XmlReaderSettings DefaultXmlReaderSettings => _defaultReaderSettings.Clone();    

        /// <summary>
        /// Serializes the given <typeparamref name="T"/> and returns the XML document as a string.
        /// </summary>
        /// <param name="o">
        /// Instance <see cref="object" /> to serialize.
        /// </param>
        public static string Serialize(T o)
        {
            StringBuilder sb = new StringBuilder();
            using (XmlWriter xmlWriter = XmlWriter.Create(sb))
                _serializer.Serialize(xmlWriter, o, (XmlSerializerNamespaces)null);
            return sb.ToString();
        }

        /// <summary>
        /// Serializes the given <typeparamref name="T"/> and returns the XML document as a string.
        /// </summary>
        /// <param name="o">
        /// Instance <see cref="object" /> to serialize.
        /// </param>
        /// <param name="settings">
        /// Settings for the new <see cref="XmlWriter" /> instance. If <see langword="null"/> is specified,
        /// settings are used <see cref="DefaultXmlWriterSettings"/>.
        /// </param>
        public static string Serialize(T o, XmlWriterSettings settings)
        {
            if (settings == null) settings = _defaultWriterSettings;
            StringBuilder sb = new StringBuilder();
            using (XmlWriter xmlWriter = XmlWriter.Create(sb, settings))
                _serializer.Serialize(xmlWriter, o, (XmlSerializerNamespaces)null);
            return sb.ToString();
        }

        /// <summary>
        /// Serializes the given <typeparamref name="T"/> and writes the XML document to a file using the given <see cref="TextWriter" />.
        /// </summary>
        /// <param name="textWriter">
        /// <see cref="TextWriter" /> Used to write an XML document.
        /// </param>
        /// <param name="o">
        /// Instance <see cref="object" /> to serialize.
        /// </param>
        public static void Serialize(TextWriter textWriter, T o)
        {
            using (XmlWriter xmlWriter = XmlWriter.Create(textWriter))
                _serializer.Serialize(textWriter, o, (XmlSerializerNamespaces)null);
        } 
        
        /// <summary>
        /// Serializes the given <typeparamref name="T"/> and writes the XML document to a file using the given <see cref="TextWriter" />.
        /// </summary>
        /// <param name="textWriter">
        /// <see cref="TextWriter" /> Used to write an XML document.
        /// </param>
        /// <param name="o">
        /// Instance <see cref="object" /> to serialize.
        /// </param>
        /// <param name="settings">
        /// Settings for the new <see cref="XmlWriter" /> instance. If <see langword="null"/> is specified,
        /// settings are used <see cref="DefaultXmlWriterSettings"/>.
        /// </param>
        public static void Serialize(TextWriter textWriter, T o, XmlWriterSettings settings)
        {
            if (settings == null) settings = _defaultWriterSettings;
            using (XmlWriter xmlWriter = XmlWriter.Create(textWriter, settings))
                _serializer.Serialize(xmlWriter, o, (XmlSerializerNamespaces)null);
        }

        /// <summary>
        /// Serializes the given <typeparamref name="T"/> and writes the XML document to a file using the given <see cref="TextWriter" /> and references to the given namespaces.
        /// </summary>
        /// <param name="textWriter">
        /// <see cref="TextWriter" /> Used to write an XML document.
        /// </param>
        /// <param name="o">
        /// Instance <see cref="object" /> to serialize.
        /// </param>
        /// <param name="namespaces">
        /// <see cref="XmlSerializerNamespaces" /> Contains the namespaces for the generated XML document.
        /// </param>
        /// <exception cref="InvalidOperationException">
        /// An error occurred during serialization.
        /// The original exception is accessible using the <see cref="P:System.Exception.InnerException" /> property.
        /// </exception>
        public static void Serialize(TextWriter textWriter, T o, XmlSerializerNamespaces namespaces)
        {
            using (XmlWriter xmlWriter = XmlWriter.Create(textWriter))
                _serializer.Serialize(xmlWriter, o, namespaces);
        } 
        
        /// <summary>
        /// Serializes the given <typeparamref name="T"/> and writes the XML document to a file using the given <see cref="TextWriter" /> and references to the given namespaces.
        /// </summary>
        /// <param name="textWriter">
        /// <see cref="TextWriter" /> Used to write an XML document.
        /// </param>
        /// <param name="o">
        /// Instance <see cref="object" /> to serialize.
        /// </param>
        /// <param name="namespaces">
        /// <see cref="XmlSerializerNamespaces" /> Contains the namespaces for the generated XML document.
        /// </param>
        /// <param name="settings">
        /// Settings for the new <see cref="XmlWriter" /> instance. If <see langword="null"/> is specified,
        /// settings are used <see cref="DefaultXmlWriterSettings"/>.
        /// </param>
        /// <exception cref="InvalidOperationException">
        /// An error occurred during serialization.
        /// The original exception is accessible using the <see cref="P:System.Exception.InnerException" /> property.
        /// </exception>
        public static void Serialize(TextWriter textWriter, T o, XmlSerializerNamespaces namespaces, XmlWriterSettings settings)
        {
            if (settings == null) settings = _defaultWriterSettings;
            using (XmlWriter xmlWriter = XmlWriter.Create(textWriter, settings))
                _serializer.Serialize(xmlWriter, o, namespaces);
        }

        /// <summary>
        /// Serializes the given <typeparamref name="T"/> and writes the XML document to a file using the given <see cref="Stream" />.
        /// </summary>
        /// <param name="stream">
        /// <see cref="Stream" /> Used to write an XML document.
        /// </param>
        /// <param name="o">
        /// Instance <see cref="object" /> to serialize.
        /// </param>
        /// <exception cref="InvalidOperationException">
        /// An error occurred during serialization.
        /// The original exception is accessible using the <see cref="P:System.Exception.InnerException" /> property.
        /// </exception>
        public static void Serialize(Stream stream, T o)
        {
            _serializer.Serialize(stream, o, (XmlSerializerNamespaces)null);
        } 
        
        /// <summary>
        /// Serializes the given <typeparamref name="T"/> and writes the XML document to a file using the given <see cref="Stream" />.
        /// </summary>
        /// <param name="stream">
        /// <see cref="Stream" /> Used to write an XML document.
        /// </param>
        /// <param name="o">
        /// Instance <see cref="object" /> to serialize.
        /// </param>
        /// <param name="settings">
        /// Settings for the new <see cref="XmlWriter" /> instance. If <see langword="null"/> is specified,
        /// settings are used <see cref="DefaultXmlWriterSettings"/>.
        /// </param>
        /// <exception cref="InvalidOperationException">
        /// An error occurred during serialization.
        /// The original exception is accessible using the <see cref="P:System.Exception.InnerException" /> property.
        /// </exception>
        public static void Serialize(Stream stream, T o, XmlWriterSettings settings)
        {
            if (settings == null) settings = _defaultWriterSettings;
            using (TextWriter writer = new StreamWriter(stream, settings.Encoding))
            using (XmlWriter xmlWriter = XmlWriter.Create(writer, settings))
                _serializer.Serialize(xmlWriter, o, (XmlSerializerNamespaces) null);
        }

        /// <summary>
        /// Serializes the given <typeparamref name="T"/> and writes the XML document to a file using the given <see cref="Stream" /> refers to the given namespaces.
        /// </summary>
        /// <param name="stream">
        /// <see cref="Stream" /> Used to write an XML document.
        /// </param>
        /// <param name="o">
        /// Instance <see cref="object" /> to serialize.
        /// </param>
        /// <param name="namespaces">
        /// <see cref="XmlSerializerNamespaces" /> The object is referenced.
        /// </param>
        /// <exception cref="InvalidOperationException">
        /// An error occurred during serialization.
        /// The original exception is accessible using the <see cref="P:System.Exception.InnerException" /> property.
        /// </exception>
        public static void Serialize(Stream stream, T o, XmlSerializerNamespaces namespaces)
        {
            _serializer.Serialize(stream, o, namespaces);
        } 
        
        /// <summary>
        /// Serializes the given <typeparamref name="T"/> and writes the XML document to a file using the given <see cref="Stream" /> refers to the given namespaces.
        /// </summary>
        /// <param name="stream">
        /// <see cref="Stream" /> Used to write an XML document.
        /// </param>
        /// <param name="o">
        /// Instance <see cref="object" /> to serialize.
        /// </param>
        /// <param name="namespaces">
        /// <see cref="XmlSerializerNamespaces" /> The object is referenced.
        /// </param>
        /// <param name="settings">
        /// Settings for the new <see cref="XmlWriter" /> instance. If <see langword="null"/> is specified,
        /// settings are used <see cref="DefaultXmlWriterSettings"/>.
        /// </param>
        /// <exception cref="InvalidOperationException">
        /// An error occurred during serialization.
        /// The original exception is accessible using the <see cref="P:System.Exception.InnerException" /> property.
        /// </exception>
        public static void Serialize(Stream stream, T o, XmlSerializerNamespaces namespaces, XmlWriterSettings settings)
        {
            if (settings == null) settings = _defaultWriterSettings;
            using (TextWriter writer = new StreamWriter(stream, settings.Encoding))
            using (XmlWriter xmlWriter = XmlWriter.Create(writer, settings))
                _serializer.Serialize(xmlWriter, o, namespaces);
        }

        /// <summary>
        /// Serializes the given <typeparamref name="T"/> and writes the XML document to a file using the given <see cref="XmlWriter" />.
        /// </summary>
        /// <param name="xmlWriter">
        /// <see cref="XmlWriter" /> Used to write an XML document.
        /// </param>
        /// <param name="o">
        /// Instance <see cref="object" /> to serialize.
        /// </param>
        /// <param name="settings">
        /// Settings for the new <see cref="XmlWriter" /> instance. If <see langword="null"/> is specified,
        /// the settings of the current <see cref="XmlWriter" /> instance are used.
        /// </param>
        /// <exception cref="InvalidOperationException">
        /// An error occurred during serialization.
        /// The original exception is accessible using the <see cref="P:System.Exception.InnerException" /> property.
        /// </exception>
        public static void Serialize(XmlWriter xmlWriter, T o, XmlWriterSettings settings = null)
        {
            using (XmlWriter writer = settings == null ? xmlWriter : XmlWriter.Create(xmlWriter, settings))
                _serializer.Serialize(writer, o, (XmlSerializerNamespaces)null); 
        }
        
        /// <summary>
        /// Serializes the given <typeparamref name="T"/> and writes the XML document to a file using the given <see cref="XmlWriter" /> and references to the given namespaces.
        /// </summary>
        /// <param name="xmlWriter">
        /// <see cref="XmlWriter" /> Used to write an XML document.
        /// </param>
        /// <param name="o">
        /// Instance <see cref="object" /> to serialize.
        /// </param>
        /// <param name="namespaces">
        /// <see cref="XmlSerializerNamespaces" /> The object is referenced.
        /// </param>
        /// <param name="settings">
        /// Settings for the new <see cref="XmlWriter" /> instance. If <see langword="null"/> is specified,
        /// the settings of the current <see cref="XmlWriter" /> instance are used.
        /// </param>
        /// <exception cref="InvalidOperationException">
        /// An error occurred during serialization.
        /// The original exception is accessible using the <see cref="P:System.Exception.InnerException" /> property.
        /// </exception>
        public static void Serialize(XmlWriter xmlWriter, T o, XmlSerializerNamespaces namespaces, XmlWriterSettings settings = null)
        {
            using (XmlWriter writer = settings == null ? xmlWriter : XmlWriter.Create(xmlWriter, settings))
                _serializer.Serialize(writer, o, namespaces);
        }

        /// <summary>
        /// Serializes the specified object and writes the XML document to a file using the specified <typeparamref name="T"/> and references the specified namespaces and encoding style.
        /// </summary>
        /// <param name="xmlWriter">
        /// <see cref="XmlWriter" /> Used to write an XML document.
        /// </param>
        /// <param name="o">Object to serialize.</param>
        /// <param name="namespaces">
        /// <see cref="XmlSerializerNamespaces" /> The object is referenced.
        /// </param>
        /// <param name="encodingStyle">
        /// The encoding style of the serialized XML.
        /// </param>
        /// <param name="settings">
        /// Settings for the new <see cref="XmlWriter" /> instance. If <see langword="null"/> is specified,
        /// the settings of the current <see cref="XmlWriter" /> instance are used.
        /// </param>
        /// <exception cref="InvalidOperationException">
        /// An error occurred during serialization.
        /// The original exception is accessible using the <see cref="P:System.Exception.InnerException" /> property.
        /// </exception>
        public static void Serialize(
            XmlWriter xmlWriter,
            T o
            XmlSerializerNamespaces,
            string encodingStyle,
            XmlWriterSettings settings = null)
        {
            using (XmlWriter writer = settings == null ? xmlWriter : XmlWriter.Create(xmlWriter, settings))
                _serializer.Serialize(writer, o, namespaces, encodingStyle, (string)null);
        } 
        
        /// <summary>
        /// Serializes the given <typeparamref name="T"/> and writes the XML document to a file using the given <see cref="XmlWriter" />, XML namespaces, and encoding.
        /// </summary>
        /// <param name="xmlWriter">
        /// <see cref="XmlWriter" /> Used to write an XML document.
        /// </param>
        /// <param name="o">Object to serialize.</param>
        /// <param name="namespaces">
        /// An instance of <see langword="XmlSerializaerNamespaces" /> containing the namespaces and prefixes used.
        /// </param>
        /// <param name="encodingStyle">
        /// The encoding used in the document.
        /// </param>
        /// <param name="id">
        /// For SOAP encoded messages, a base is used to generate identifier attributes.
        /// </param>
        /// <param name="settings">
        /// Settings for the new <see cref="XmlWriter" /> instance. If <see langword="null"/> is specified,
        /// the settings of the current <see cref="XmlWriter" /> instance are used.
        /// </param>
        public static void Serialize(
            XmlWriter xmlWriter,
            T o
            XmlSerializerNamespaces,
            string encodingStyle,
            string id,
            XmlWriterSettings settings = null)
        {
            using (XmlWriter writer = settings == null ? xmlWriter : XmlWriter.Create(xmlWriter, settings))
                _serializer.Serialize(writer, o, namespaces, encodingStyle, id);
        } 
        
        /// <summary>
        /// Deserializes the XML document contained in the specified string.
        /// </summary>
        /// settings are used <see cref="DefaultXmlReaderSettings"/>.</param>
        /// <returns> The deserialized object <typeparamref name="T"/>. </returns>
        public static T Deserialize(string text)
        {
            using (StringReader reader = new StringReader(text))
            using (XmlReader xmlReader = XmlReader.Create(reader))
                return (T)_serializer.Deserialize(xmlReader);

        }

        /// <summary>
        /// Deserializes the XML document contained in the specified string.
        /// </summary>
        /// <param name="text">String containing the XML document.</param>
        /// <param name="settings"> Settings for the new <see cref="XmlReader" /> instance. If <see langword="null"/> is specified,
        /// settings are used <see cref="DefaultXmlReaderSettings"/>.</param>
        /// <returns> The deserialized object <typeparamref name="T"/>. </returns>
        public static T Deserialize(string text, XmlReaderSettings settings)
        {
            if (settings == null) settings = _defaultReaderSettings;
            using (StringReader reader = new StringReader(text))
            using (XmlReader xmlReader = XmlReader.Create(reader, settings))
                return (T)_serializer.Deserialize(xmlReader);

        }

        /// <summary>
        /// Deserializes the XML document contained in the specified <see cref="Stream" />.
        /// </summary>
        /// <param name="stream">
        /// <see cref="Stream" /> Containing the XML document to deserialize.
        /// </param>
        /// <returns>
        /// Deserialized object <typeparamref name="T"/>.
        /// </returns>
        public static T Deserialize(Stream stream)
        {
                return (T)_serializer.Deserialize(stream);
        } 
        
        /// <summary>
        /// Deserializes the XML document contained in the specified <see cref="Stream" />.
        /// </summary>
        /// <param name="stream">
        /// <see cref="Stream" /> Containing the XML document to deserialize.
        /// </param>
        /// <param name="settings">Settings for the new <see cref="XmlReader" /> instance. If <see langword="null"/> is specified,
        /// settings are used <see cref="DefaultXmlReaderSettings"/>.</param>
        /// <returns>
        /// Deserialized object <typeparamref name="T"/>.
        /// </returns>
        public static T Deserialize(Stream stream, XmlReaderSettings settings)
        {
            if (settings == null) settings = _defaultReaderSettings;
            using(XmlReader xmlReader = XmlReader.Create(stream, settings))
                return (T)_serializer.Deserialize(xmlReader);
        }

        /// <summary>
        /// Deserializes the XML document contained in the specified <see cref="TextReader" />.
        /// </summary>
        /// <param name="textReader">
        /// <see cref="TextReader" /> The containing XML document to deserialize.
        /// </param>
        /// <returns>
        /// Deserialized object <typeparamref name="T"/>.
        /// </returns>
        /// <exception cref="InvalidOperationException">
        /// An error occurred during deserialization.
        /// The original exception is accessible using the <see cref="P:System.Exception.InnerException" /> property.
        /// </exception>
        public static T Deserialize(TextReader textReader)
        {
            return (T) _serializer.Deserialize(textReader);
        }

        /// <summary>
        /// Deserializes the XML document contained in the specified <see cref="TextReader" />.
        /// </summary>
        /// <param name="textReader">
        /// <see cref="TextReader" /> The containing XML document to deserialize.
        /// </param>
        /// <param name="settings">Settings for the new <see cref="XmlReader" /> instance. If <see langword="null"/> is specified,
        /// settings are used <see cref="DefaultXmlReaderSettings"/>.</param>
        /// <returns>
        /// Deserialized object <typeparamref name="T"/>.
        /// </returns>
        /// <exception cref="InvalidOperationException">
        /// An error occurred during deserialization.
        /// The original exception is accessible using the <see cref="P:System.Exception.InnerException" /> property.
        /// </exception>
        public static T Deserialize(TextReader textReader, XmlReaderSettings settings)
        {
            if (settings == null) settings = _defaultReaderSettings;
            using (XmlReader xmlReader = XmlReader.Create(textReader, settings))
                return (T)_serializer.Deserialize(xmlReader);
        } 
        
        /// <summary>
        /// Deserializes the XML document contained in the specified <see cref="XmlReader" />.
        /// </summary>
        /// <param name="xmlReader">
        /// <see cref="XmlReader" /> The containing XML document to deserialize.
        /// </param>
        /// <param name="settings">Settings for the new <see cref="XmlReader" /> instance. If <see langword="null"/> is specified,
        /// current instance settings are used <see cref="XmlReader" />.</param>
        /// <returns>
        /// Deserialized object <typeparamref name="T"/>.
        /// </returns>
        /// <exception cref="InvalidOperationException">
        /// An error occurred during deserialization.
        /// The original exception is accessible using the <see cref="P:System.Exception.InnerException" /> property.
        /// </exception>
        public static T Deserialize(XmlReader xmlReader, XmlReaderSettings settings = null)
        {
            using (XmlReader reader = settings == null ? xmlReader : XmlReader.Create(xmlReader, settings))
                return (T)_serializer.Deserialize(xmlReader);
        }

        /// <summary>
        /// Deserializes the XML document contained in the specified <see cref="XmlReader" /> and allows you to override events that occur during deserialization.
        /// </summary>
        /// <param name="xmlReader">
        /// <see cref="XmlReader" /> The containing document to deserialize.
        /// </param>
        /// <param name="events">
        /// Class instance <see cref="XmlDeserializationEvents" />.
        /// </param>
        /// <param name="settings">Settings for the new <see cref="XmlReader" /> instance. If <see langword="null"/> is specified,
        /// current instance settings are used <see cref="XmlReader" />.</param>
        /// <returns>
        /// Deserialized object <typeparamref name="T"/>.
        /// </returns>
        public static T Deserialize(XmlReader xmlReader, XmlDeserializationEvents events, XmlReaderSettings settings = null)
        {
            using (XmlReader reader = settings == null ? xmlReader : XmlReader.Create(xmlReader, settings))
                return (T)_serializer.Deserialize(reader, (string)null, events);
        }

        /// <summary>
        /// Deserializes the XML document contained in the specified <see cref="XmlReader" /> and encoding style.
        /// </summary>
        /// <param name="xmlReader">
        /// <see cref="XmlReader" /> The containing XML document to deserialize.
        /// </param>
        /// <param name="encodingStyle">
        /// The encoding style of the serialized XML.
        /// </param>
        /// <param name="settings">Settings for the new <see cref="XmlReader" /> instance. If <see langword="null"/> is specified,
        /// current instance settings are used <see cref="XmlReader" />.</param>
        /// <returns>The deserialized object.</returns>
        /// <exception cref="InvalidOperationException">
        /// An error occurred during deserialization.
        /// The original exception is accessible using the <see cref="P:System.Exception.InnerException" /> property.
        /// </exception>
        public static T Deserialize(XmlReader xmlReader, string encodingStyle, XmlReaderSettings settings = null)
        {
            using (XmlReader reader = settings == null ? xmlReader : XmlReader.Create(xmlReader, settings))
                return (T)_serializer.Deserialize(reader, encodingStyle);
        }

        /// <summary>
        /// Deserializes the object using the data contained in the specified <see cref="XmlReader" />.
        /// </summary>
        /// <param name="xmlReader">
        /// An instance of the <see cref="XmlReader" /> class used to read the document.
        /// </param>
        /// <param name="encodingStyle">Encoding used.</param>
        /// <param name="events">
        /// Class instance <see cref="XmlDeserializationEvents" />.
        /// </param>
        /// <param name="settings">Settings for the new <see cref="XmlReader" /> instance. If <see langword="null"/> is specified,
        /// current instance settings are used <see cref="XmlReader" />.</param>
        /// <returns>The deserialized object <typeparamref name="T"/>.</returns>
        public static object Deserialize(
            xmlReader xmlReader,
            string encodingStyle,
            XmlDeserializationEvents events,
            XmlReaderSettings settings = null)
        {
            using (XmlReader reader = settings == null ? xmlReader : XmlReader.Create(xmlReader, settings))
                return _serializer.Deserialize(reader, encodingStyle, events);
        }

        /// <summary>
        /// Returns a value indicating whether this <see cref="XmlSerializer" /> can deserialize the specified XML document.
        /// </summary>
        /// <param name="xmlReader">
        /// <see cref="XmlReader" /> Pointing to the document to deserialize.
        /// </param>
        /// <returns>
        /// <see langword="true" /> If this <see cref="XmlSerializer" /> can deserialize an object, <see cref="XmlReader" /> indicates; otherwise, <see langword="false" />.
        /// </returns>
        public static bool CanDeserialize(XmlReader xmlReader)
        {
            return _serializer.CanDeserialize(xmlReader);
        } 
    }
}   

基于上述解决方案,这里有一个扩展类,您可以使用它序列化和反序列化任何对象。任何其他XML属性都由您决定。

就像这样使用它:

        string s = new MyObject().Serialize(); // to serialize into a string
        MyObject b = s.Deserialize<MyObject>();// deserialize from a string



internal static class Extensions
{
    public static T Deserialize<T>(this string value)
    {
        var xmlSerializer = new XmlSerializer(typeof(T));

        return (T)xmlSerializer.Deserialize(new StringReader(value));
    }

    public static string Serialize<T>(this T value)
    {
        if (value == null)
            return string.Empty;

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

        using (var stringWriter = new StringWriter())
        {
            using (var xmlWriter = XmlWriter.Create(stringWriter, new XmlWriterSettings { Indent = true }))
            {
                xmlSerializer.Serialize(xmlWriter, value);
                return stringWriter.ToString();
            }
        }
    }
}