Serializes and deserializes between an object and an XML document. XmlSerializer enables you to control how objects are encoded as XML.
namespaces: System.Xml.Serialization
Assemblies: System.Xml (located in System.Xml.dll)
Here is an example to illustrate:
//This was the class that would be serialized. Public classordereditem{ Public stringItemName; Public stringDescription; Public decimalUnitPrice; Public intQuantity; Public decimalLineTotal; //A custom method used to calculate price per item. Public voidCalculate () {LineTotal= UnitPrice *Quantity; }}
How to convert this class into an XML file, this time you need to XmlSerializer class to deal with.
It's serialize (Stream,?) Object) This method is used to convert an object of the user class into an XML document.
Let's look at an example:
usingSystem;usingSystem.IO;usingSystem.Xml.Serialization; Public classtest{ Public Static voidMain (string[] args) {Test T=NewTest (); //Write a purchase order.T.serializeobject ("Simple.xml"); } Private voidSerializeObject (stringfilename) {Console.WriteLine ("Writing with Stream"); XmlSerializer Serializer=NewXmlSerializer (typeof(Ordereditem)); Ordereditem I=NewOrdereditem (); I.itemname="Widgets"; I.description="Regular Widget"; I.quantity=Ten; I.unitprice= (decimal)2.30; I.calculate (); //Create a FileStream to write with.Stream writer =NewFileStream (filename, filemode.create); //Serialize the object, and close the TextWriterSerializer. Serialize (writer, i); Writer. Close (); }}
The resulting XML file is in the following format:
<?xml version="1.0"?> <ordereditem xmlns:inventory="http// www.cpandl.com "xmlns:money="http://www.cohowinery.com"> < inventory:itemname>widget</inventory:itemname> <inventory:description>regular Widget</ inventory:description> <money:UnitPrice>2.3</money:UnitPrice> < inventory:quantity></inventory:Quantity> <money:LineTotal> </ Money:linetotal> </OrderedItem>
Examples of serialize (Stream,object) methods for XmlSerializer classes in the C # language