C# XML 序列化覆盖 IXmlSerializable 类型 Class
C# XML serialization override Type of IXmlSerializable Class
初始问题
我想 serialize
List<IXmlSerializable>
动态更改 IXmlSerializable
class 的 XmlType(这样我就可以'不要使用属性标签来做到这一点)
我已经尝试使用 XmlAttributeOverrides 来做到这一点,但到目前为止没有成功。
下面是说明该问题的示例代码:
IXmlSerializable class(来自 MSDN):
public class Person : IXmlSerializable
{
// Private state
private string personName;
// Constructors
public Person(string name)
{
personName = name;
}
public Person()
{
personName = null;
}
// Xml Serialization Infrastructure
public void WriteXml(XmlWriter writer)
{
writer.WriteString(personName);
}
public void ReadXml(XmlReader reader)
{
personName = reader.ReadString();
}
public XmlSchema GetSchema()
{
return (null);
}
// Print
public override string ToString()
{
return (personName);
}
}
测试class(使用控制台输出):
class Program
{
static void Main(string[] args)
{
List<Person> lPersonList = new List<Person> {
new Person("First"),
new Person("Second"),
new Person("Third")
};
XmlAttributeOverrides lOverrides = new XmlAttributeOverrides();
XmlAttributes lAttributes = new XmlAttributes { XmlType = new XmlTypeAttribute("Employee") };
lOverrides.Add(typeof(Person), lAttributes);
XmlSerializer lSerialiser = new XmlSerializer(typeof(List<Person>), lOverrides, null, new XmlRootAttribute("Employees"), null);
XmlSerializerNamespaces lNamespaces = new XmlSerializerNamespaces();
lNamespaces.Add("", "");
lSerialiser.Serialize(Console.Out, lPersonList, lNamespaces);
System.Console.WriteLine("Enter any key to close.");
System.Console.ReadKey();
}
}
这是我想要得到的:
<Employees>
<Employee>First</Employee>
<Employee>Second</Employee>
<Employee>Third</Employee>
</Employees>
但是我在运行时遇到这个错误:
System.InvalidOperationException: Only XmlRoot attribute may be specified for the type Person. Please use XmlSchemaProviderAttribute to specify schema type.
注意 当我的 人 class 没有实施 IXmlSerializable
时,一切正常...
有人可以帮我吗?
选择方案(基于)
正如@dbc 指出的那样,使用 "surrogate" class 是做我想做的最简单的方法。但是正如我所说,我需要动态更改 Person 类型,这意味着我不能使用属性标签。
所以我在最终设计中仍然使用XmlAttributeOverrides
,这里是:
Surrogate List<Person>
Class (与没有属性标签的@dbc 相同):
public class EmployeesListSurrogate
{
public List<Person> EmployeeList { get; set; }
public static implicit operator List<Person>(EmployeesListSurrogate surrogate)
{
return surrogate == null ? null : surrogate.EmployeeList;
}
public static implicit operator EmployeesListSurrogate(List<Person> employees)
{
return new EmployeesListSurrogate { EmployeeList = employees };
}
}
使用代理测试class:
class Program
{
static void Main(string[] args)
{
List<Person> lPersonList = new List<Person> {
new Person("First"),
new Person("Second"),
new Person("Third")
};
XmlAttributeOverrides lOverrides = new XmlAttributeOverrides();
XmlAttributes lEmployeesListAttributes = new XmlAttributes { XmlRoot = new XmlRootAttribute("Employees") };
lOverrides.Add(typeof(EmployeesListSurrogate), lEmployeesListAttributes);
XmlAttributes lEmployeeAttributes = new XmlAttributes { XmlElements = { new XmlElementAttribute("Employee") } };
lOverrides.Add(typeof(EmployeesListSurrogate), "EmployeeList", lEmployeeAttributes);
XmlSerializer lSerializer = new XmlSerializer(typeof(EmployeesListSurrogate), lOverrides);
XmlSerializerNamespaces lNamespaces = new XmlSerializerNamespaces();
lNamespaces.Add("", "");
lSerializer.Serialize(Console.Out, (EmployeesListSurrogate)lPersonList, lNamespaces);
}
}
我想以非常感谢@dbc 来结束这篇文章,你的回答非常有帮助和信息丰富,我学到了很多东西。我不能给你投票,但我希望社区会这样做!
获得您想要的 XML 的最简单方法是序列化 "surrogate" class,如下所示:
[XmlRoot("Employees")]
public class EmployeesListSurrogate
{
[XmlElement("Employee")]
public List<Person> EmployeeList { get; set; }
public static implicit operator List<Person>(EmployeesListSurrogate surrogate)
{
return surrogate == null ? null : surrogate.EmployeeList;
}
public static implicit operator EmployeesListSurrogate(List<Person> employees)
{
return new EmployeesListSurrogate { EmployeeList = employees };
}
}
这完全消除了 XmlAttributeOverrides
的需要。或者您可以使用 XmlAttributeOverrides
和 XmlAttributes.XmlElements
动态地为 EmployeeList
指定 XML 名称。
也就是说,当您尝试将 [XmlType]
应用于也实现了 IXmlSerializable
的类型时抛出 InvalidOperationException
的原因是 XmlSerializer
需要该类型名称将通过完全不同的机制 return 编辑,即 XmlSchemaProviderAttribute.MethodName
method specified in an [XmlSchemaProvider]
属性。
当 [XmlSchemaProvider]
应用于 IXmlSerializable
类型时,XmlSerializer
将查找名称在属性构造函数中指定的类型的 public 静态方法,并且具有以下签名:
public static XmlQualifiedName GetSchemaMethod(XmlSchemaSet xs)
{
}
此方法的目的有两个:
序列化该类型的实例时,它应该用预期的模式填充XmlSchemaSet
。通过测试,我发现它必须填充有效的东西。不能留空,否则会抛出异常
(我不知道 XmlSerializer
在序列化时实际在多大程度上验证了模式。通过 xsd.exe
导出模式信息时也会调用该方法。)
它应该return XML 类型名称。
这似乎是 Microsoft 抛出您所看到的异常的原因:由于架构属性提供程序应该 return 类型名称,因此 XmlType
属性会发生冲突。
因此,如果我修改你的 Person
class 如下:
[XmlSchemaProvider("GetSchemaMethod")]
public class Person : IXmlSerializable
{
// Private state
private string personName;
// Constructors
public Person(string name)
{
personName = name;
}
public Person()
{
personName = null;
}
// This is the method named by the XmlSchemaProviderAttribute applied to the type.
public static XmlQualifiedName GetSchemaMethod(XmlSchemaSet xs)
{
string EmployeeSchema = @"<?xml version=""1.0"" encoding=""utf-16""?>
<xs:schema elementFormDefault=""qualified"" xmlns:xs=""http://www.w3.org/2001/XMLSchema"">
<xs:import namespace=""http://www.w3.org/2001/XMLSchema"" />
<xs:element name=""Employee"" nillable=""true"" type=""Employee"" />
<xs:complexType name=""Employee"" mixed=""true"">
<xs:sequence>
<xs:any />
</xs:sequence>
</xs:complexType>
</xs:schema>";
using (var textReader = new StringReader(EmployeeSchema))
using (var schemaSetReader = System.Xml.XmlReader.Create(textReader))
{
xs.Add("", schemaSetReader);
}
return new XmlQualifiedName("Employee");
}
// Xml Serialization Infrastructure
public void WriteXml(XmlWriter writer)
{
writer.WriteString(personName);
}
public void ReadXml(XmlReader reader)
{
reader.MoveToContent();
var isEmpty = reader.IsEmptyElement;
reader.ReadStartElement();
if (!isEmpty)
{
personName = reader.ReadContentAsString();
reader.ReadEndElement();
}
}
public XmlSchema GetSchema()
{
return (null);
}
// Print
public override string ToString()
{
return (personName);
}
}
并将您的 List<Person>
序列化为 XML,我得到以下结果:
<ArrayOfEmployee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Employee>First</Employee>
<Employee>Second</Employee>
<Employee>Third</Employee>
</ArrayOfEmployee>
如您所见,已成功指定 Person
的 XML 类型名称。
但是,您想通过 XmlAttributeOverrides
动态覆盖 Person
的 XML 类型名称,而不是将其设置为编译类型。为此,似乎有必要在 XmlAttributes
中指定一个 XmlSchemaProviderAttribute
。不幸的是,在 XmlAttributes
中找不到 XmlSchemaProvider
属性。 看来 Microsoft 从未实现过此类功能。因此,如果你想进一步追求这个设计,你将需要做一些笨拙的事情:在创建覆盖序列化程序时临时覆盖 GetSchemaMethod()
的 return。要记住两件事:
在幕后,XmlSerializer
通过创建动态程序集来工作。如果您使用 new XmlSerializer(Type)
或 new XmlSerializer(Type, String)
构造一个 XmlSerializer
,则 .Net 将缓存程序集并在第二次构造序列化程序时重用它。
因此,在使用其中任何一个构建序列化程序时尝试临时覆盖 GetSchemaMethod()
的 return 将失败或产生意外结果。
否则,动态程序集不会缓存,因此您的代码必须手动缓存序列化器,否则会有严重的资源泄漏。参见 Memory Leak using StreamReader and XmlSerializer。
在这些情况下,暂时覆盖 GetSchemaMethod()
的 return 可能有效。
综上所述,以下内容生成您需要的 XML:
[XmlSchemaProvider("GetSchemaMethod")]
public class Person : IXmlSerializable
{
// Private state
private string personName;
// Constructors
public Person(string name)
{
personName = name;
}
public Person()
{
personName = null;
}
[ThreadStatic]
static string personXmlTypeName;
const string defaultXmlTypeName = "Person";
static string PersonXmlTypeName
{
get
{
if (personXmlTypeName == null)
personXmlTypeName = defaultXmlTypeName;
return personXmlTypeName;
}
set
{
personXmlTypeName = value;
}
}
public static IDisposable PushXmlTypeName(string xmlTypeName)
{
return new PushValue<string>(xmlTypeName, () => PersonXmlTypeName, val => PersonXmlTypeName = val);
}
// This is the method named by the XmlSchemaProviderAttribute applied to the type.
public static XmlQualifiedName GetSchemaMethod(XmlSchemaSet xs)
{
string EmployeeSchemaFormat = @"<?xml version=""1.0"" encoding=""utf-16""?>
<xs:schema elementFormDefault=""qualified"" xmlns:xs=""http://www.w3.org/2001/XMLSchema"">
<xs:import namespace=""http://www.w3.org/2001/XMLSchema"" />
<xs:element name=""{0}"" nillable=""true"" type=""{0}"" />
<xs:complexType name=""{0}"" mixed=""true"">
<xs:sequence>
<xs:any />
</xs:sequence>
</xs:complexType>
</xs:schema>";
var EmployeeSchema = string.Format(EmployeeSchemaFormat, PersonXmlTypeName);
using (var textReader = new StringReader(EmployeeSchema))
using (var schemaSetReader = System.Xml.XmlReader.Create(textReader))
{
xs.Add("", schemaSetReader);
}
return new XmlQualifiedName(PersonXmlTypeName);
}
// Xml Serialization Infrastructure
public void WriteXml(XmlWriter writer)
{
writer.WriteString(personName);
}
public void ReadXml(XmlReader reader)
{
reader.MoveToContent();
var isEmpty = reader.IsEmptyElement;
reader.ReadStartElement();
if (!isEmpty)
{
personName = reader.ReadContentAsString();
reader.ReadEndElement();
}
}
public XmlSchema GetSchema()
{
return (null);
}
// Print
public override string ToString()
{
return (personName);
}
}
public struct PushValue<T> : IDisposable
{
Action<T> setValue;
T oldValue;
public PushValue(T value, Func<T> getValue, Action<T> setValue)
{
if (getValue == null || setValue == null)
throw new ArgumentNullException();
this.setValue = setValue;
this.oldValue = getValue();
setValue(value);
}
#region IDisposable Members
// By using a disposable struct we avoid the overhead of allocating and freeing an instance of a finalizable class.
public void Dispose()
{
if (setValue != null)
setValue(oldValue);
}
#endregion
}
public static class PersonEmployeeListSerializerFactory
{
static Dictionary<Tuple<string, string>, XmlSerializer> serializers;
static object padlock = new object();
static PersonEmployeeListSerializerFactory()
{
serializers = new Dictionary<Tuple<string, string>, XmlSerializer>();
}
public static XmlSerializer GetSerializer(string rootName, string personName)
{
lock (padlock)
{
XmlSerializer serializer;
var key = Tuple.Create(rootName, personName);
if (!serializers.TryGetValue(key, out serializer))
{
using (Person.PushXmlTypeName(personName))
{
var lOverrides = new XmlAttributeOverrides();
//var lAttributes = new XmlAttributes();
//lOverrides.Add(typeof(Person), lAttributes);
serializers[key] = serializer = new XmlSerializer(typeof(List<Person>), lOverrides, new Type[0], new XmlRootAttribute(rootName), null);
}
}
return serializer;
}
}
}
然后做
var lSerialiser = PersonEmployeeListSerializerFactory.GetSerializer("Employees", "Employee");
var lNamespaces = new XmlSerializerNamespaces();
lNamespaces.Add("", "");
var sb = new StringBuilder();
using (var writer = new StringWriter(sb))
lSerialiser.Serialize(writer, lPersonList, lNamespaces);
Console.WriteLine(sb);
但是如您所见,这比使用最初显示的代理要复杂得多。
显示两个选项的示例 fiddle。
初始问题
我想 serialize
List<IXmlSerializable>
动态更改 IXmlSerializable
class 的 XmlType(这样我就可以'不要使用属性标签来做到这一点)
我已经尝试使用 XmlAttributeOverrides 来做到这一点,但到目前为止没有成功。
下面是说明该问题的示例代码:
IXmlSerializable class(来自 MSDN):
public class Person : IXmlSerializable
{
// Private state
private string personName;
// Constructors
public Person(string name)
{
personName = name;
}
public Person()
{
personName = null;
}
// Xml Serialization Infrastructure
public void WriteXml(XmlWriter writer)
{
writer.WriteString(personName);
}
public void ReadXml(XmlReader reader)
{
personName = reader.ReadString();
}
public XmlSchema GetSchema()
{
return (null);
}
// Print
public override string ToString()
{
return (personName);
}
}
测试class(使用控制台输出):
class Program
{
static void Main(string[] args)
{
List<Person> lPersonList = new List<Person> {
new Person("First"),
new Person("Second"),
new Person("Third")
};
XmlAttributeOverrides lOverrides = new XmlAttributeOverrides();
XmlAttributes lAttributes = new XmlAttributes { XmlType = new XmlTypeAttribute("Employee") };
lOverrides.Add(typeof(Person), lAttributes);
XmlSerializer lSerialiser = new XmlSerializer(typeof(List<Person>), lOverrides, null, new XmlRootAttribute("Employees"), null);
XmlSerializerNamespaces lNamespaces = new XmlSerializerNamespaces();
lNamespaces.Add("", "");
lSerialiser.Serialize(Console.Out, lPersonList, lNamespaces);
System.Console.WriteLine("Enter any key to close.");
System.Console.ReadKey();
}
}
这是我想要得到的:
<Employees>
<Employee>First</Employee>
<Employee>Second</Employee>
<Employee>Third</Employee>
</Employees>
但是我在运行时遇到这个错误:
System.InvalidOperationException: Only XmlRoot attribute may be specified for the type Person. Please use XmlSchemaProviderAttribute to specify schema type.
注意 当我的 人 class 没有实施 IXmlSerializable
时,一切正常...
有人可以帮我吗?
选择方案(基于)
正如@dbc 指出的那样,使用 "surrogate" class 是做我想做的最简单的方法。但是正如我所说,我需要动态更改 Person 类型,这意味着我不能使用属性标签。
所以我在最终设计中仍然使用XmlAttributeOverrides
,这里是:
Surrogate List<Person>
Class (与没有属性标签的@dbc 相同):
public class EmployeesListSurrogate
{
public List<Person> EmployeeList { get; set; }
public static implicit operator List<Person>(EmployeesListSurrogate surrogate)
{
return surrogate == null ? null : surrogate.EmployeeList;
}
public static implicit operator EmployeesListSurrogate(List<Person> employees)
{
return new EmployeesListSurrogate { EmployeeList = employees };
}
}
使用代理测试class:
class Program
{
static void Main(string[] args)
{
List<Person> lPersonList = new List<Person> {
new Person("First"),
new Person("Second"),
new Person("Third")
};
XmlAttributeOverrides lOverrides = new XmlAttributeOverrides();
XmlAttributes lEmployeesListAttributes = new XmlAttributes { XmlRoot = new XmlRootAttribute("Employees") };
lOverrides.Add(typeof(EmployeesListSurrogate), lEmployeesListAttributes);
XmlAttributes lEmployeeAttributes = new XmlAttributes { XmlElements = { new XmlElementAttribute("Employee") } };
lOverrides.Add(typeof(EmployeesListSurrogate), "EmployeeList", lEmployeeAttributes);
XmlSerializer lSerializer = new XmlSerializer(typeof(EmployeesListSurrogate), lOverrides);
XmlSerializerNamespaces lNamespaces = new XmlSerializerNamespaces();
lNamespaces.Add("", "");
lSerializer.Serialize(Console.Out, (EmployeesListSurrogate)lPersonList, lNamespaces);
}
}
我想以非常感谢@dbc 来结束这篇文章,你的回答非常有帮助和信息丰富,我学到了很多东西。我不能给你投票,但我希望社区会这样做!
获得您想要的 XML 的最简单方法是序列化 "surrogate" class,如下所示:
[XmlRoot("Employees")]
public class EmployeesListSurrogate
{
[XmlElement("Employee")]
public List<Person> EmployeeList { get; set; }
public static implicit operator List<Person>(EmployeesListSurrogate surrogate)
{
return surrogate == null ? null : surrogate.EmployeeList;
}
public static implicit operator EmployeesListSurrogate(List<Person> employees)
{
return new EmployeesListSurrogate { EmployeeList = employees };
}
}
这完全消除了 XmlAttributeOverrides
的需要。或者您可以使用 XmlAttributeOverrides
和 XmlAttributes.XmlElements
动态地为 EmployeeList
指定 XML 名称。
也就是说,当您尝试将 [XmlType]
应用于也实现了 IXmlSerializable
的类型时抛出 InvalidOperationException
的原因是 XmlSerializer
需要该类型名称将通过完全不同的机制 return 编辑,即 XmlSchemaProviderAttribute.MethodName
method specified in an [XmlSchemaProvider]
属性。
当 [XmlSchemaProvider]
应用于 IXmlSerializable
类型时,XmlSerializer
将查找名称在属性构造函数中指定的类型的 public 静态方法,并且具有以下签名:
public static XmlQualifiedName GetSchemaMethod(XmlSchemaSet xs)
{
}
此方法的目的有两个:
序列化该类型的实例时,它应该用预期的模式填充
XmlSchemaSet
。通过测试,我发现它必须填充有效的东西。不能留空,否则会抛出异常(我不知道
XmlSerializer
在序列化时实际在多大程度上验证了模式。通过xsd.exe
导出模式信息时也会调用该方法。)它应该return XML 类型名称。
这似乎是 Microsoft 抛出您所看到的异常的原因:由于架构属性提供程序应该 return 类型名称,因此
XmlType
属性会发生冲突。
因此,如果我修改你的 Person
class 如下:
[XmlSchemaProvider("GetSchemaMethod")]
public class Person : IXmlSerializable
{
// Private state
private string personName;
// Constructors
public Person(string name)
{
personName = name;
}
public Person()
{
personName = null;
}
// This is the method named by the XmlSchemaProviderAttribute applied to the type.
public static XmlQualifiedName GetSchemaMethod(XmlSchemaSet xs)
{
string EmployeeSchema = @"<?xml version=""1.0"" encoding=""utf-16""?>
<xs:schema elementFormDefault=""qualified"" xmlns:xs=""http://www.w3.org/2001/XMLSchema"">
<xs:import namespace=""http://www.w3.org/2001/XMLSchema"" />
<xs:element name=""Employee"" nillable=""true"" type=""Employee"" />
<xs:complexType name=""Employee"" mixed=""true"">
<xs:sequence>
<xs:any />
</xs:sequence>
</xs:complexType>
</xs:schema>";
using (var textReader = new StringReader(EmployeeSchema))
using (var schemaSetReader = System.Xml.XmlReader.Create(textReader))
{
xs.Add("", schemaSetReader);
}
return new XmlQualifiedName("Employee");
}
// Xml Serialization Infrastructure
public void WriteXml(XmlWriter writer)
{
writer.WriteString(personName);
}
public void ReadXml(XmlReader reader)
{
reader.MoveToContent();
var isEmpty = reader.IsEmptyElement;
reader.ReadStartElement();
if (!isEmpty)
{
personName = reader.ReadContentAsString();
reader.ReadEndElement();
}
}
public XmlSchema GetSchema()
{
return (null);
}
// Print
public override string ToString()
{
return (personName);
}
}
并将您的 List<Person>
序列化为 XML,我得到以下结果:
<ArrayOfEmployee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Employee>First</Employee>
<Employee>Second</Employee>
<Employee>Third</Employee>
</ArrayOfEmployee>
如您所见,已成功指定 Person
的 XML 类型名称。
但是,您想通过 XmlAttributeOverrides
动态覆盖 Person
的 XML 类型名称,而不是将其设置为编译类型。为此,似乎有必要在 XmlAttributes
中指定一个 XmlSchemaProviderAttribute
。不幸的是,在 XmlAttributes
中找不到 XmlSchemaProvider
属性。 看来 Microsoft 从未实现过此类功能。因此,如果你想进一步追求这个设计,你将需要做一些笨拙的事情:在创建覆盖序列化程序时临时覆盖 GetSchemaMethod()
的 return。要记住两件事:
在幕后,
XmlSerializer
通过创建动态程序集来工作。如果您使用new XmlSerializer(Type)
或new XmlSerializer(Type, String)
构造一个XmlSerializer
,则 .Net 将缓存程序集并在第二次构造序列化程序时重用它。因此,在使用其中任何一个构建序列化程序时尝试临时覆盖
GetSchemaMethod()
的 return 将失败或产生意外结果。否则,动态程序集不会缓存,因此您的代码必须手动缓存序列化器,否则会有严重的资源泄漏。参见 Memory Leak using StreamReader and XmlSerializer。
在这些情况下,暂时覆盖
GetSchemaMethod()
的 return 可能有效。
综上所述,以下内容生成您需要的 XML:
[XmlSchemaProvider("GetSchemaMethod")]
public class Person : IXmlSerializable
{
// Private state
private string personName;
// Constructors
public Person(string name)
{
personName = name;
}
public Person()
{
personName = null;
}
[ThreadStatic]
static string personXmlTypeName;
const string defaultXmlTypeName = "Person";
static string PersonXmlTypeName
{
get
{
if (personXmlTypeName == null)
personXmlTypeName = defaultXmlTypeName;
return personXmlTypeName;
}
set
{
personXmlTypeName = value;
}
}
public static IDisposable PushXmlTypeName(string xmlTypeName)
{
return new PushValue<string>(xmlTypeName, () => PersonXmlTypeName, val => PersonXmlTypeName = val);
}
// This is the method named by the XmlSchemaProviderAttribute applied to the type.
public static XmlQualifiedName GetSchemaMethod(XmlSchemaSet xs)
{
string EmployeeSchemaFormat = @"<?xml version=""1.0"" encoding=""utf-16""?>
<xs:schema elementFormDefault=""qualified"" xmlns:xs=""http://www.w3.org/2001/XMLSchema"">
<xs:import namespace=""http://www.w3.org/2001/XMLSchema"" />
<xs:element name=""{0}"" nillable=""true"" type=""{0}"" />
<xs:complexType name=""{0}"" mixed=""true"">
<xs:sequence>
<xs:any />
</xs:sequence>
</xs:complexType>
</xs:schema>";
var EmployeeSchema = string.Format(EmployeeSchemaFormat, PersonXmlTypeName);
using (var textReader = new StringReader(EmployeeSchema))
using (var schemaSetReader = System.Xml.XmlReader.Create(textReader))
{
xs.Add("", schemaSetReader);
}
return new XmlQualifiedName(PersonXmlTypeName);
}
// Xml Serialization Infrastructure
public void WriteXml(XmlWriter writer)
{
writer.WriteString(personName);
}
public void ReadXml(XmlReader reader)
{
reader.MoveToContent();
var isEmpty = reader.IsEmptyElement;
reader.ReadStartElement();
if (!isEmpty)
{
personName = reader.ReadContentAsString();
reader.ReadEndElement();
}
}
public XmlSchema GetSchema()
{
return (null);
}
// Print
public override string ToString()
{
return (personName);
}
}
public struct PushValue<T> : IDisposable
{
Action<T> setValue;
T oldValue;
public PushValue(T value, Func<T> getValue, Action<T> setValue)
{
if (getValue == null || setValue == null)
throw new ArgumentNullException();
this.setValue = setValue;
this.oldValue = getValue();
setValue(value);
}
#region IDisposable Members
// By using a disposable struct we avoid the overhead of allocating and freeing an instance of a finalizable class.
public void Dispose()
{
if (setValue != null)
setValue(oldValue);
}
#endregion
}
public static class PersonEmployeeListSerializerFactory
{
static Dictionary<Tuple<string, string>, XmlSerializer> serializers;
static object padlock = new object();
static PersonEmployeeListSerializerFactory()
{
serializers = new Dictionary<Tuple<string, string>, XmlSerializer>();
}
public static XmlSerializer GetSerializer(string rootName, string personName)
{
lock (padlock)
{
XmlSerializer serializer;
var key = Tuple.Create(rootName, personName);
if (!serializers.TryGetValue(key, out serializer))
{
using (Person.PushXmlTypeName(personName))
{
var lOverrides = new XmlAttributeOverrides();
//var lAttributes = new XmlAttributes();
//lOverrides.Add(typeof(Person), lAttributes);
serializers[key] = serializer = new XmlSerializer(typeof(List<Person>), lOverrides, new Type[0], new XmlRootAttribute(rootName), null);
}
}
return serializer;
}
}
}
然后做
var lSerialiser = PersonEmployeeListSerializerFactory.GetSerializer("Employees", "Employee");
var lNamespaces = new XmlSerializerNamespaces();
lNamespaces.Add("", "");
var sb = new StringBuilder();
using (var writer = new StringWriter(sb))
lSerialiser.Serialize(writer, lPersonList, lNamespaces);
Console.WriteLine(sb);
但是如您所见,这比使用最初显示的代理要复杂得多。
显示两个选项的示例 fiddle。