问题
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;
}
}
This serializes without error but the resulting XML does not include the Text property since it does not have a public setter.
Is there a way (the simpler, the better) to have the XmlSerializer include those properties?
回答1:
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;
}
}
This works on both public and private members, but the xml produced is not quite the same, and you can't specify xml attributes.
回答2:
No. XML Serialization will only serialized public read/write fields and properties of objects.
回答3:
Try[Serializable] public class Something { ... }
来源:https://stackoverflow.com/questions/1065849/xmlserializer-with-parameterless-constructor-with-no-public-properties-or-fields