XML Serialization with C#
Wanna know a easy way to serialize your class to XML ???
Here we go…
This is the class myXMLSerializer.cs
We gonna need System.IO, System.Text and, of course, System.Xml.Serialization.
using System;
using System.IO;
using System.Data;
using System.Text;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
I created a sealed class with one static method to make a common XML Serializer for my app, use as you wish.
namespace how2do.XML
{
public sealed class myXMLSerializer
{
public static XmlDocument SerializeObject(Type type, object objToSerialize)
{
Now we create a MemoryStream because we don’t want a file stream or whatever we see in a lot of examples over the internet, I just wanted to work with string-memory-XmlDocument… (I was so pissed off because I couldn’t find something similar, people assume we are always using .xml files)
// Serialization
MemoryStream mStream = new MemoryStream();
Here, the correct parameter shall be: … = new XmlSerializer(typeof(YourClass)); Ok?
XmlSerializer objSerializer = new XmlSerializer(type);
I got a lot of problems using UTF8 here (to create the stream) and also using UTF8 converting to string
//must be Encoding.Default due problems with UTF8Enconding which is used to get the XML as string
XmlTextWriter xmlWriter = new XmlTextWriter(mStream, Encoding.Default);
objSerializer.Serialize(xmlWriter, objToSerialize);
Now, taking the damn XML as string. Let’s create our beloved XmlDocument.
XmlDocument xmlObject = new XmlDocument();
I’m using UTF8, don’t remember why… ah! XmlDocument.LoadXml is a pain in the ass, UFT8 works great =)
UTF8Encoding encoding = new UTF8Encoding();
mStream = (MemoryStream)xmlWriter.BaseStream;
The trick
string strXML = encoding.GetString(mStream.ToArray());
Now loading into the XmlDocument using LoadXml(), not Load() because Load() is for files and files sucks.
xmlObject.LoadXml(strXML);
return xmlObject;
}
}
}
ABOUT THE CLASSES YOU WILL SERIALIZE
Don’t forget to use the XML Attributes into the classes you want to serialize.
- using System.Xml.Serialization;
- A parameterless contructor to your class, OR the class simply WON’T serialize
- [XmlAttribute] and others Attributes
- [XmlIgnore] in get/set property where can return a class which one you dont want/cannot create a parameterless constructor
If you have some property like this:
public string Name
{
get { return this.strName; }
}
You must put a empty set otherwise the XML Serializer won’t get it (your class WILL be serialized but without james:
public string Name
{
get { return this.strName; }
set { }
}
Using:
XmlDocument xml = myXMLSerializer.SerializeObject(typeof(yourclass), yourinstance));
=)