将对象序列化为 XML
Posted
技术标签:
【中文标题】将对象序列化为 XML【英文标题】:Serialize an object to XML 【发布时间】:2011-05-06 15:11:57 【问题描述】:我有一个我继承的 C# 类。我已经成功地“构建”了对象。但我需要。有什么简单的方法吗?
看起来该类已设置为进行序列化,但我不确定如何获取 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 表示形式?
【问题讨论】:
另请参阅:XML Serialization and Deserialization on CodeProject 我开发了一个简单的库来实现这一点:github.com/aishwaryashiva/SaveXML 【参考方案1】:您必须使用 XmlSerializer 进行 XML 序列化。下面是一个示例 sn-p。
XmlSerializer xsSubmit = new XmlSerializer(typeof(MyObject));
var subReq = new MyObject();
var xml = "";
using(var sww = new StringWriter())
using(XmlWriter writer = XmlWriter.Create(sww))
xsSubmit.Serialize(writer, subReq);
xml = sww.ToString(); // Your XML
根据@kiquenet 对泛型类的请求:
public class MySerializer<T> where T : class
public static string Serialize(T obj)
XmlSerializer xsSubmit = new XmlSerializer(typeof(T));
using (var sww = new StringWriter())
using (XmlTextWriter writer = new XmlTextWriter(sww) Formatting = Formatting.Indented )
xsSubmit.Serialize(writer, obj);
return sww.ToString();
用法:
string xmlMessage = MySerializer<MyClass>.Serialize(myObj);
【讨论】:
没有XmlWriter writer = XmlWriter.Create(sww);
这一行似乎工作得很好
要格式化序列化对象:XmlTextWriter writer = new XmlTextWriter(sww) Formatting = Formatting.Indented ;
而不是XmlWriter writer = XmlWriter.Create(sww);
既然XmlWriter
封装了StringWriter
,你就不需要同时处理这两个(第一次使用是多余的),对吧?我假设XmlWriter
负责处理它......
@talles XmlWriter
没有封装StringWriter
,它正在使用您传入的StringWriter
,并且没有期望/责任处置它。此外,StringWriter
超出了XmlWriter
的范围,当XmlWriter
被处置时,您可能仍然需要它,XmlWriter
处置您的StringWriter
将是不良行为。作为一般规则,如果您声明需要处理的东西,您有责任处理它。并且隐含在该规则中,任何你不声明自己的东西都不应该处理。所以using
s 都是必要的。
使用 System.Xml.Serialization;使用 System.IO;使用 System.Xml;【参考方案2】:
我修改了我的返回一个字符串,而不是像下面这样使用 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();
【讨论】:
非常好的解决方案,我喜欢您将其实现为扩展方法的方式 我在这里建议的一件事:删除 try...catch 块。它不会给您带来任何好处,只会混淆引发的错误。 你不需要在stringwriter上使用吗?例如:使用(var stringWriter = new StringWriter()) @jammycakes 不!当您在那里抛出一个新的Exception
时,您已经使用“Serialize”方法扩展了 StackTrace。
@user2190035 如果要在扩展方法中中断,堆栈跟踪肯定会从那里开始吗?用try“扩展堆栈跟踪”似乎没有必要?【参考方案3】:
可以将以下函数复制到任何对象,以使用 System.Xml 命名空间添加 XML 保存函数。
/// <summary>
/// Saves to an xml file
/// </summary>
/// <param name="FileName">File path of the new xml file</param>
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();
要从保存的文件创建对象,添加以下函数并将 [ObjectType] 替换为要创建的对象类型。
/// <summary>
/// Load an object from an xml file
/// </summary>
/// <param name="FileName">Xml file name</param>
/// <returns>The object created from the xml file</returns>
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];
【讨论】:
writer.Flush()
在 using
块中是多余的 - writer
的 Dispose()
方法将为您刷新它。
我的经验发现这不是真的。对于较大的数据,using 语句将在缓冲区被清除之前处理流。我 100% 建议明确调用 flush。
writer.Flush() 不是多余的,它必须存在。如果没有 Flush,可能会发生部分数据仍在 StreamWriter 缓冲区中并且文件被释放并且丢失一些数据的情况。
我非常喜欢你的代码:简短而整洁。我的问题是一次又一次地将函数复制到不同的类:不是代码重复吗?其他答案建议使用模板扩展方法的通用库,我会接受。你怎么看?【参考方案4】:
扩展类:
using System.IO;
using System.Xml;
using System.Xml.Serialization;
namespace MyProj.Extensions
public static class XmlExtension
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 XmlWriterSettingsIndent = true))
xmlSerializer.Serialize(xmlWriter, value);
return stringWriter.ToString();
用法:
Foo foo = new FooMyProperty="I have been serialized";
string xml = foo.Serialize();
只需在您想使用它的文件中引用包含您的扩展方法的命名空间,它就会起作用(在我的示例中为:using MyProj.Extensions;
)
请注意,如果您想让扩展方法只针对特定类(例如,Foo
),您可以替换扩展方法中的T
参数,例如。
public static string Serialize(this Foo value)...
【讨论】:
【参考方案5】:您可以使用下面的函数从任何对象获取序列化的 XML。
public static bool Serialize<T>(T value, ref string serializeXml)
if (value == null)
return false;
try
XmlSerializer xmlserializer = new XmlSerializer(typeof(T));
StringWriter stringWriter = new StringWriter();
XmlWriter writer = XmlWriter.Create(stringWriter);
xmlserializer.Serialize(writer, value);
serializeXml = stringWriter.ToString();
writer.Close();
return true;
catch (Exception ex)
return false;
您可以从客户端调用它。
【讨论】:
【参考方案6】:以上所有赞成的答案都是正确的。这只是最简单的版本:
private string Serialize(Object o)
using (var writer = new StringWriter())
new XmlSerializer(o.GetType()).Serialize(writer, o);
return writer.ToString();
【讨论】:
【参考方案7】:要序列化对象,请执行以下操作:
using (StreamWriter myWriter = new StreamWriter(path, false))
XmlSerializer mySerializer = new XmlSerializer(typeof(your_object_type));
mySerializer.Serialize(myWriter, objectToSerialize);
还请记住,要使 XmlSerializer 工作,您需要一个无参数构造函数。
【讨论】:
这让我发疯了。我不明白为什么它总是空白。然后在阅读您的答案后意识到我没有没有参数的构造函数。谢谢。【参考方案8】:我将从 Ben Gripka 的复制答案开始:
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();
我之前使用过这段代码。但现实表明,这种解决方案有点问题。通常大多数程序员只是在保存时序列化设置并在加载时反序列化设置。这是一个乐观的情况。一旦序列化失败,由于某种原因,文件被部分写入,XML文件不完整,无效。结果 XML 反序列化不起作用,您的应用程序可能在启动时崩溃。如果文件不是很大,我建议先将对象序列化为MemoryStream
,然后将流写入文件。如果有一些复杂的自定义序列化,这种情况尤其重要。您永远无法测试所有案例。
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();
【讨论】:
在将 MemoryStream 写入文件时,进程是否可能被中断,例如断电? 是的,有可能。您可以通过将设置写入临时文件然后替换原始文件来避免它。【参考方案9】:比调用类的ToString
方法稍微复杂一点,但也不多。
这是一个简单的插入函数,可用于序列化任何类型的对象。它返回一个包含序列化 XML 内容的字符串:
public string SerializeObject(object obj)
System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(obj.GetType());
using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
serializer.Serialize(ms, obj);
ms.Position = 0;
xmlDoc.Load(ms);
return xmlDoc.InnerXml;
【讨论】:
【参考方案10】:我有一种使用 C# 将对象序列化为 XML 的简单方法,它工作得很好,并且高度可重用。我知道这是一个较旧的帖子,但我想发布此帖子,因为有人可能会发现这对他们有帮助。
我是这样称呼这个方法的:
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);
【讨论】:
【参考方案11】:基于上述解决方案,这里有一个扩展类,您可以使用它来序列化和反序列化任何对象。任何其他 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();
【讨论】:
感谢您展示用法:字符串 = "" 的反序列化返回什么? 我想我已经准备好了解决方案,我是一名复制粘贴程序员 :) // ***.com/questions/6529611/c-sharp-create-new-t public static T DeserializeHere is a good tutorial on how to do this
您应该基本上使用System.Xml.Serialization.XmlSerializer
类来执行此操作。
【讨论】:
【参考方案13】:我的工作代码。返回 utf8 xml 启用空命名空间。
// override StringWriter
public class Utf8StringWriter : StringWriter
public override Encoding Encoding => Encoding.UTF8;
private string GenerateXmlResponse(Object obj)
Type t = obj.GetType();
var xml = "";
using (StringWriter sww = new Utf8StringWriter())
using (XmlWriter writer = XmlWriter.Create(sww))
var ns = new XmlSerializerNamespaces();
// add empty namespace
ns.Add("", "");
XmlSerializer xsSubmit = new XmlSerializer(t);
xsSubmit.Serialize(writer, obj, ns);
xml = sww.ToString(); // Your XML
return xml;
示例返回响应 Yandex api 支付 Aviso url:
<?xml version="1.0" encoding="utf-8"?><paymentAvisoResponse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" performedDatetime="2017-09-01T16:22:08.9747654+07:00" code="0" shopId="54321" invoiceId="12345" orderSumAmount="10643" />
【讨论】:
嗨@dev-siberia,我正在使用你的代码,但它以字符串形式返回xml,这意味着所有内容都用双引号引起来。【参考方案14】: string FilePath = ConfigurationReader.FileLocation; //Getting path value from web.config
XmlSerializer serializer = new XmlSerializer(typeof(Devices)); //typeof(object)
MemoryStream memStream = new MemoryStream();
serializer.Serialize(memStream, lstDevices);//lstdevices : I take result as a list.
FileStream file = new FileStream(folderName + "\\Data.xml", FileMode.Create, FileAccess.ReadWrite); //foldername:Specify the path to store the xml file
memStream.WriteTo(file);
file.Close();
您可以创建结果并将其作为 xml 文件存储在所需位置。
【讨论】:
【参考方案15】:或者您可以将此方法添加到您的对象中:
public void Save(string filename)
var ser = new XmlSerializer(this.GetType());
using (var stream = new FileStream(filename, FileMode.Create))
ser.Serialize(stream, this);
【讨论】:
【参考方案16】:这是一个有助于将 C# 对象序列化为 xml 的基本代码:
using System;
public class clsPerson
public string FirstName;
public string MI;
public string LastName;
class class1
static void Main(string[] args)
clsPerson p=new clsPerson();
p.FirstName = "Jeff";
p.MI = "A";
p.LastName = "Price";
System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(p.GetType());
x.Serialize(Console.Out, p);
Console.WriteLine();
Console.ReadLine();
【讨论】:
如果您引用此代码的来源会很好:support.microsoft.com/en-us/help/815813/…【参考方案17】:public string ObjectToXML(object input)
try
var stringwriter = new System.IO.StringWriter();
var serializer = new XmlSerializer(input.GetType());
serializer.Serialize(stringwriter, input);
return stringwriter.ToString();
catch (Exception ex)
if (ex.InnerException != null)
ex = ex.InnerException;
return "Could not convert: " + ex.Message;
//Usage
var res = ObjectToXML(obj)
您需要使用以下类:
using System.IO;
using System.Xml;
using System.Xml.Serialization;
【讨论】:
【参考方案18】:这是一个通用的对象序列化器:
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);
【讨论】:
【参考方案19】:聚会可能为时已晚,但只有用户定义的命名空间有序列化:
public static string XmlSerialize<T>(this T obj) where T : class
Type serialType = typeof(T);
var xsSubmit = new XmlSerializer(serialType);
XmlWriterSettings xws = new XmlWriterSettings() OmitXmlDeclaration = true, Indent = true ;
var Namespaces = new XmlSerializerNamespaces(new XmlQualifiedName[]
new XmlQualifiedName(string.Empty, GetXmlNameSpace(serialType) ?? string.Empty )
);
private static string GetXmlNameSpace(Type target)
XmlRootAttribute attribute = (XmlRootAttribute)Attribute.GetCustomAttribute(target, typeof(XmlRootAttribute));
return attribute == null ? null : attribute.Namespace;
并在自定义类中定义命名空间
[XmlRoot("IdentityTerminal",Namespace = "http://my-name-space/XMLSchema")]
public class IdentityTerminal
此代码仅允许用户使用用户定义的命名空间并省略默认命名空间。
【讨论】:
以上是关于将对象序列化为 XML的主要内容,如果未能解决你的问题,请参考以下文章
将 Xml 反序列化为对象时出错 - xmlns='' 不是预期的