问题描述
具有以下类(.Net 3.5):
Having the following class (.Net 3.5):
public class Something
{
public string Text {get; private set;}
private Something()
{
Text = string.Empty;
}
public Something(string text)
{
Text = text;
}
}
此序列化没有错误,但是由于XML没有公共设置器,因此生成的XML不包含Text属性.
This serializes without error but the resulting XML does not include the Text property since it does not have a public setter.
有没有办法(更简单,更好)让XmlSerializer包含那些属性?
Is there a way (the simpler, the better) to have the XmlSerializer include those properties?
推荐答案
XmlSerializer
只关心公共的读/写成员.一种选择是实现 IXmlSerializable
,但这是一项很多的工作.一个更实用的选择(如果可用且合适)可能是使用 DataContractSerializer
:
XmlSerializer
only cares about public read/write members. One option is to implement IXmlSerializable
, but that is a lot of work. A more practical option (if available and suitable) may be to use DataContractSerializer
:
[DataContract]
public class Something
{
[DataMember]
public string Text {get; private set;}
private Something()
{
Text = string.Empty;
}
public Something(string text)
{
Text = text;
}
}
这对公共和私有成员均有效,但是生成的xml不太相同,并且您不能指定xml属性.
This works on both public and private members, but the xml produced is not quite the same, and you can't specify xml attributes.
这篇关于带有无参数构造函数的XmlSerializer,没有公共属性或字段...是否可能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!