XmlSerialization in .NET part 2
Well, apparently in my last post on the subject, I neglected to mention the way to Serialize from an object instance to an Xml file. So, in this installment I’m planning to compensate for my somewhat lacking introduction to Xml Serialization
So … serializing to Xml is actually a very simple process. if you recall the example from my previous post, we ‘ve had a class called ClassDescriptor, which has two public properties. I’ve included the Serialization-related attributes in my class definition, and we’ve de-serialized from an Xml file.
This time, I want to reverse the process. To do that, I’ve included another static method to my XmlUtils class:
public static void Serialize(object instance, Stream io_out){
XmlSerializer ser = new XmlSerializer(instance.GetType());
ser.Serialize(new System.Xml.XmlTextWriter(new StreamWriter(io_out)), instance);
}
As you can see, serializing is just a matter of creating an XmlTextWriter on a stream, and calling Serialize(…) on the XmlSerializer.
Here’s the modified code in the Main(…) method. It continues from where we’ve just deserialized an instance of ClassDescriptor, and what it does is simple. It opens a stream to a new file, and passes it to the XmlUtils.Serialize(object, Stream) method:
Stream io_out = new FileStream("../../out_class.xml", FileMode.Create, FileAccess.Write);
XmlUtils.Serialize(classDescr, io_out);
io_out.Close();
No big thing, is it ? Running the program will create a new file called out_class.xml, which contains the following Xml:
<?xml version="1.0" encoding="utf-8"?>
<class
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
class-name="System.Int32"
assembly-name="System"
/>
As you can see, the only difference between the xml we used to deserialize into an object is the two xmlns attributes. Those are inserted automatically by the XmlSerializer output. I don’t particularly enjoy having the framework insert stuff into my Xml, but it can’t be avoided
When I find the solution, i’ll be sure to post it though.
Until then, and until I find the time to write another blog entry on more advanced Xml Serialization issues, have a nice code-day ! You can find the updated source for this example here
O:]