I'm quite newbie to C#. I've started to use SGEN generated XmlSerializers.dll and I'm really confused right now. Despite that I cannot find any true step by step tutorial how to use it properly I'm also confused by different advices.
I read a lot of SGEN articles and I'm still not sure how to use generated lib in my project.
Does any one who has real-coding practice with this can explain me once and for all the proper way to use it?
I was thinking that I understood how to use it but yesterday I found this tutorial: http://www.dotnetfunda.com/articles/article1105-optimized-way-of-xml-serialization-using-sgen-utility-.aspx
The guy has added .XmlSerializers.dll to his Project references and uses code like this to Serialize:
static string SerializebySGEN()
{
Person p = new Person();
p.Age = 29;
p.Name = "Satya Narayan Sahoo";
StringBuilder buildr = new StringBuilder();
StringWriter writr = new System.IO.StringWriter(buildr);
PersonSerializer mySerialzer = new PersonSerializer();
mySerialzer.Serialize(writr, p);
string str = writr.ToString();
return str;
}
PersonSerializer mySerialzer = new PersonSerializer();
but on stackoverflow in the past somebody wrote to my another question connected to XmlSerializers:
Adding a reference is not necessary, Xml serialization always tries an Assembly.Load() on the .XmlSerializers.dll assembly anyway. > Plus, you'll never reference the generated XmlSerializationWriterXxx and XmlSerializationReaderXxx classes directly in your code.
So who is right? Can somne practitioner tell me how I should use this SGEN generated library with my project and code? I really want to use it in good way! :)
Edit: or maybe I misudnerstood something in quoted articles and both person have right? I'm lost :)
Edit2: I wrote below method to deserialize one of my Serializable Classes (MySerializableClass) and I use SGEN generated class MySerializableClassSerializer. Is this ok? (I think so, plz confirm ;))
/// <summary>
/// Deserializes the specified XML source into object using SGEN generated class.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="xmlSource">The XML source.</param>
/// <param name="isFile">if set to <c>true</c> the the source is a text File else it is a XML String.</param>
/// <returns>Return object with deserialized XML</returns>
public static MySerializableClass MySerializableClassSgenDeserialize(string xmlSource, bool isFile = true)
{
MySerializableClass data = new MySerializableClass();
if (isFile)
{
using (TextReader textReader = new StreamReader(xmlSource))
{
MySerializableClassSerializer xSerializer = new MySerializableClassSerializer();
data = (MySerializableClass)xSerializer.Deserialize(textReader);
}
}
else
{
using (StringReader xmlText = new StringReader(xmlSource))
{
MySerializableClassSerializer xSerializer = new MySerializableClassSerializer();
data = (MySerializableClass)xSerializer.Deserialize(xmlText);
}
}
return data;
}