我有一个实现IXmlSerializable
我正在序列化的类型DataContractSerializer
。在将根元素序列化为 XML 文档的根元素时,如何控制根元素的命名空间和名称?
假设我有以下类型:
public partial class PersonDTO : IXmlSerializable
{
public string Name { get; set; }
#region IXmlSerializable Members
public System.Xml.Schema.XmlSchema GetSchema()
{
return null;
}
public void ReadXml(System.Xml.XmlReader reader)
{
Name = reader["name"];
if (!reader.IsEmptyElement)
reader.Skip();
reader.Read();
}
public void WriteXml(System.Xml.XmlWriter writer)
{
writer.WriteAttributeString("name", Name);
}
#endregion
}
如果我将它DataContractSerializer
作为我的根对象序列化,我会得到:
<PersonDTO name="John Doe" xmlns="http://schemas.datacontract.org/2004/07/MyClrNamespace" />
我希望根名称为<Person>
,根名称空间为"http://www.MyCompany.com"
,所以我尝试[DataContract]
像这样添加:
[DataContract(Name = "Person", Namespace = "http://www.MyCompany.com")]
public partial class PersonDTO : IXmlSerializable
{
}
但是当我这样做时,DataContractSerializer
会抛出一个异常,说明Type 'PersonDTO' cannot be IXmlSerializable 并且具有 DataContractAttribute 属性:
System.Runtime.Serialization.InvalidDataContractException occurred
Message="Type 'PersonDTO' cannot be IXmlSerializable and have DataContractAttribute attribute."
Source="System.Runtime.Serialization"
StackTrace:
at System.Runtime.Serialization.XmlDataContract.XmlDataContractCriticalHelper..ctor(Type type)
at System.Runtime.Serialization.XmlDataContract..ctor(Type type)
at System.Runtime.Serialization.DataContract.DataContractCriticalHelper.CreateDataContract(Int32 id, RuntimeTypeHandle typeHandle, Type type)
at System.Runtime.Serialization.DataContract.DataContractCriticalHelper.GetDataContractSkipValidation(Int32 id, RuntimeTypeHandle typeHandle, Type type)
at System.Runtime.Serialization.DataContract.GetDataContract(RuntimeTypeHandle typeHandle, Type type, SerializationMode mode)
at System.Runtime.Serialization.DataContractSerializer.get_RootContract()
DataContractSerializer(Type type, String rootName, String rootNamespace)
我知道手动序列化时可以使用构造函数修改根名称和命名空间:
var person = new PersonDTO { Name = "John Doe", };
var serializer = new DataContractSerializer(typeof(PersonDTO), "Person", @"http://www.MyCompany.com");
var sb = new StringBuilder();
using (var textWriter = new StringWriter(sb))
using (var xmlWriter = XmlWriter.Create(textWriter))
{
serializer.WriteObject(xmlWriter, person);
}
Console.WriteLine(sb);
// Outputs <Person name="John Doe" xmlns="http://www.MyCompany.com" />
但是有没有办法通过属性自动做到这一点?