I have the class and structure shown below. If I serialize the class as using xmlserializer, I get:
<Test><TestNumber1> 5 </ TestNumber1><InnerTest / "></ Test>
what is the easiest way to serialize InnerTest properly (preferably using xmlserializer) without providing the Number a setter property?
Thanks Nick
public class Test { private InnerTest innerTest; private int testNumber; public Test() { this.innerTest = new InnerTest(); this.testNumber = 5; } public int TestNumber1 { get { return this.testNumber; } set { this.testNumber = value;} } public InnerTest InnerTest { get { return this.innerTest; } set { this.innerTest = value;} } } public struct InnerTest { private int number; public InnerTest(int number) { this.number = number; } public int Number{get { return number; }} }
, IXmlSerializable XmlSerializer, , get/set , - , ( - , , DateTime, ).
IXmlSerializable
XmlSerializer
DateTime
, , .NET , DataContractSerializer, , (, DataMemberAttribute ). XML- ( - , !), , .
DataContractSerializer
DataMemberAttribute
( -, , XmlSerializer , DataContractSerializer, , , .)
, DataContractSerializer (.NET 3.0), - :
[DataMember] public int TestNumber1 { get { return this.testNumber; } set { this.testNumber = value;} } // note **not** a data-member public InnerTest InnerTest { get { return this.innerTest; } set { this.innerTest = value;} } [DataMember] private int InnerTestValue { get {return innerTest.Number;} set {innerTest = new InnerTest(value);} }
. XmlSerializer, InnerTestValue ( [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - ).
InnerTestValue
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
, ... . , , . , [de] ( ) .
- POCO, , ; , .
, , IXmlSerializable.
, , - . XmlSerializer , , ( ), , , .
, (, DateTime)... , XmlSerializer.
XmlSerializer :
Test test = new Test { TestNumber1 = 5 }; XmlSerializer xmlSer = new XmlSerializer(typeof(Test)); MemoryStream memStm = new MemoryStream(); xmlSer.Serialize(memStm, test);
, ( ):
StreamReader stmR = new StreamReader(memStm); memStm.Position = 0; string output = stmR.ReadToEnd();
If you do nothing, all the public properties of the class you are serializing will display as XML elements ..... in your resulting XML.
There are many attributes, such as [XmlIgnore] and many others, to configure them if necessary.
Enjoy it!