I have a class that handles XMLs serialization.
public class DB
{
public List<Connection> lstConnections { get; set; }
static string sRootAttribute = "Connections";
public static DB LoadFromFile(string path)
{
FileStream fs = null;
DB db = null;
try
{
fs = File.Open(path, FileMode.Open);
var serializer = new XmlSerializer(typeof(DB), new XmlRootAttribute(sRootAttribute));
db = (DB)serializer.Deserialize(fs);
}
catch
{
}
if (fs != null)
{
fs.Close();
}
return db;
}
public static void SaveToFile(string path, object objData)
{
var fs = File.Open(path, FileMode.Create);
var serializer = new XmlSerializer(objData.GetType(), new XmlRootAttribute(sRootAttribute));
try
{
serializer.Serialize(fs, objData);
}
catch
{
}
fs.Close();
}
}
The LoadFromFile method is somewhat generic, because it doesn't consider the serialized data type.
However, SaveToFile does GetType on the object that is being serialized.
Therefore, when I'm trying to deserialize the file with LoadFromFile I'm having problems. I'm not getting any exceptions, but the lstConnections is empty.
If you have ownership over the Connection class, then:
Decorate the Connection class with [System.SerializableAttribute()] and [System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)].
Decorate the connections list property with [System.Xml.Serialization.XmlArrayItemAttribute("connection", IsNullable=false)]. Though I guess you will be safer with an array and a property that's not auto implemented.
Decorate the DB class with: [System.SerializableAttribute()], [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)] and [System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
All public properties of Connection that return primitive types will get automatically serialized. Unless you specifically decorate them with [System.Xml.Serialization.XmlAttributeAttribute()], then they'll be serialized as attributes.
You must also handle serialization for non primitive return type properties of Connection similarly. Decorate properties that return collections with XmlArrayItemAttribute and mark each custom subtype as serializable.
Related
I know this is a popular topic and I have researched extensively without finding an answer to my problem.
I have a base class IntroductionAction and 2 derived classes IntroductionActionComplex and IntroductionActionSimple. I have a list of IntroductionAction objects to which I have added objects of both of the derived types. My classes are as follows:
[XmlInclude(typeof(IntroductionActionComplex))]
[XmlInclude(typeof(IntroductionActionSimple))]
public class IntroductionAction
{
public IntroductionAction() { }
}
public class IntroductionActionComplex : IntroductionAction
{
[XmlIgnore]
public string name { get; set; }
[XmlElement(ElementName = "QuestionString")]
public string question { get; set; }
[XmlElement(ElementName = "AnswerString")]
public List<string> answerStrings { get; set; }
public IntroductionActionComplex()
{
name = string.Empty;
question = null;
answerStrings = new List<string>();
}
}
public class IntroductionActionSimple : IntroductionAction
{
[XmlIgnore]
public string name { get; set; }
[XmlText]
public string Value { get; set; }
public IntroductionActionSimple()
{
Value = string.Empty;
}
}
I then create the List as follows
[XmlElement("IntroductionAction")]
public List<IntroductionAction> introductionActions { get; set; }
I am using XmlSerializer and everything serializes correctly. This is the resulting XML of the list containing one of each of the derived classes which is correct.
<IntroductionAction>
<QuestionString>
test
</QuestionString>
<AnswerString>
test
</AnswerString>
<AnswerString>
test
</AnswerString>
</IntroductionAction>
<IntroductionAction>
test
</IntroductionAction>
This XML file is going onto a device which doesn't read it as XML but just searches for the tags and does whatever work it needs to do and because of that the file can't contain any XSI or XSD tags, indentation, etc that is usually associated with proper XML.
My deserialization code is straight forward:
public static T Deserialize_xml_Config<T>(string file1, T obj)
{
XmlSerializer deserializer = new XmlSerializer(obj.GetType());
using (TextReader reader = new StreamReader(file1))
{
return (T)deserializer.Deserialize(reader);
}
}
Finally to my problem. When I deserialize, it is being deserialized to the base class IntroductionAction and not to the derived classes.
These IntroductionAction classes are just part of a much larger object that I am serializing/deserializing. I have tried making the base class abstract since it contains no functionality but I get an error on deserialization saying
The specified type is abstract: name='IntroductionAction'
Despite my XmlIncludes it seems unable to find the derived classes.
I have tried adding the types to the serializer but that didn't work.
Any help is much appreciated.
Edit:
This is what I mean by adding the types to the serializer
XmlSerializer deserializer = new XmlSerializer(obj.GetType(), new Type [] { typeof(IntroductionActionComplex), typeof(IntroductionActionSimple) });
using (TextReader reader = new StreamReader(file1))
{
return (T)deserializer.Deserialize(reader);
}
Also my attempt at using XmlAttributeOverrides:
XmlAttributeOverrides attrOverrides = new XmlAttributeOverrides();
var attrs = new XmlAttributes();
XmlElementAttribute attr = new XmlElementAttribute();
attr.ElementName = "IntroductionAction";
attr.Type = typeof(IntroductionActionComplex);
attrs.XmlElements.Add(attr);
attr.ElementName = "IntroductionAction";
attr.Type = typeof(IntroductionActionSimple);
attrs.XmlElements.Add(attr);
attrOverrides.Add(typeof(IntroductionAction), "IntroductionAction", attrs);
XmlSerializer deserializer = new XmlSerializer(obj.GetType(), attrOverrides);
using (TextReader reader = new StreamReader(file1))
{
return (T)deserializer.Deserialize(reader);
}
I think you are pretty close. Below is the full example of saving and loading the XML file based on derived class types. This will save the nodes as the derived type itself, so loading back in will keep the desired type, rather than convert back to the base type. You'll probably need to add exception handling, this was just a quick solution. I did not change your base IntroductionAction or the derived IntroductionActionComplex / IntroductionActionSimple classes.
public class RootNode
{
[XmlElement("IntroductionAction")]
public List<IntroductionAction> introductionActions { get; set; }
public RootNode()
{
introductionActions = new List<IntroductionAction>();
}
private static XmlAttributeOverrides GetXmlAttributeOverrides()
{
XmlAttributeOverrides xml_attr_overrides = new XmlAttributeOverrides();
XmlAttributes xml_attrs = new XmlAttributes();
xml_attrs.XmlElements.Add(new XmlElementAttribute(typeof(IntroductionActionComplex)));
xml_attrs.XmlElements.Add(new XmlElementAttribute(typeof(IntroductionActionSimple)));
xml_attr_overrides.Add(typeof(RootNode), "introductionActions", xml_attrs);
return xml_attr_overrides;
}
// Add exception handling
public static void SaveToFile(RootNode rootNode, string fileName)
{
using (MemoryStream mem_stream = new MemoryStream())
{
XmlSerializer serializer = new XmlSerializer(rootNode.GetType(), RootNode.GetXmlAttributeOverrides());
serializer.Serialize(mem_stream, rootNode);
using (BinaryWriter output = new BinaryWriter(new FileStream(fileName, FileMode.Create)))
{
output.Write(mem_stream.ToArray());
}
}
}
// Add exception handling
public static RootNode LoadFromFile(string fileName)
{
if (File.Exists(fileName))
{
using (FileStream file = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
using (TextReader reader = new StreamReader(file))
{
XmlSerializer serializer = new XmlSerializer(typeof(RootNode), RootNode.GetXmlAttributeOverrides());
return (RootNode)serializer.Deserialize(reader);
}
}
}
return null;
}
}
Test program:
internal class Program
{
private static void Main(string[] args)
{
RootNode obj = new RootNode();
obj.introductionActions.Add(new IntroductionActionComplex() { question = "qTest", answerStrings = { "aTest1", "aTest2" }, name = "aName1" });
obj.introductionActions.Add(new IntroductionActionSimple() { name = "aName2", Value = "aValue" });
RootNode.SaveToFile(obj, "Test.xml");
RootNode obj2 = RootNode.LoadFromFile("Test.xml");
}
}
I am using Serialization and De serialization for parsing and creating XML content. Is there any Design pattern available particularly for this serialization in C# , so that the design pattern can be used for efficient handling of serialization ?
Depending on the use case, 'DataContract' may be a good way for you to serialize/deserialize your objects -
https://msdn.microsoft.com/en-us/library/vstudio/system.runtime.serialization.datacontractattribute%28v=vs.100%29.aspx
namespace DataContractAttributeExample
{
// Set the Name and Namespace properties to new values.
[DataContract(Name = "Customer", Namespace = "http://www.contoso.com")]
class Person : IExtensibleDataObject
{
// To implement the IExtensibleDataObject interface, you must also
// implement the ExtensionData property.
private ExtensionDataObject extensionDataObjectValue;
public ExtensionDataObject ExtensionData
{
get
{
return extensionDataObjectValue;
}
set
{
extensionDataObjectValue = value;
}
}
[DataMember(Name = "CustName")]
internal string Name;
[DataMember(Name = "CustID")]
internal int ID;
public Person(string newName, int newID)
{
Name = newName;
ID = newID;
}
}
class Test
{
public static void Main()
{
try
{
WriteObject("DataContractExample.xml");
ReadObject("DataContractExample.xml");
Console.WriteLine("Press Enter to end");
Console.ReadLine();
}
catch (SerializationException se)
{
Console.WriteLine
("The serialization operation failed. Reason: {0}",
se.Message);
Console.WriteLine(se.Data);
Console.ReadLine();
}
}
public static void WriteObject(string path)
{
// Create a new instance of the Person class and
// serialize it to an XML file.
Person p1 = new Person("Mary", 1);
// Create a new instance of a StreamWriter
// to read and write the data.
FileStream fs = new FileStream(path,
FileMode.Create);
XmlDictionaryWriter writer = XmlDictionaryWriter.CreateTextWriter(fs);
DataContractSerializer ser =
new DataContractSerializer(typeof(Person));
ser.WriteObject(writer, p1);
Console.WriteLine("Finished writing object.");
writer.Close();
fs.Close();
}
public static void ReadObject(string path)
{
// Deserialize an instance of the Person class
// from an XML file. First create an instance of the
// XmlDictionaryReader.
FileStream fs = new FileStream(path, FileMode.OpenOrCreate);
XmlDictionaryReader reader =
XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas());
// Create the DataContractSerializer instance.
DataContractSerializer ser =
new DataContractSerializer(typeof(Person));
// Deserialize the data and read it from the instance.
Person newPerson = (Person)ser.ReadObject(reader);
Console.WriteLine("Reading this object:");
Console.WriteLine(String.Format("{0}, ID: {1}",
newPerson.Name, newPerson.ID));
fs.Close();
}
}
}
Want seralization to be an "opt-in" process so that only fields with a [DataMember] attribute show up in the xml.
Looked at DataContractSerializerSettings, but doesn't seem to have anything. Tried below for kicks and giggles, but the xml still contained properties that did not have the [DataMember] attribute...
DataContractSerializer writer =
new DataContractSerializer( typeof( ProductAAnimals ),
new DataContractSerializerSettings()
{
IgnoreExtensionDataObject = true
} );
With .NET 3.5 SP1, Members decorated with [DataMember], any public read/write property will be serialized automatically by the DataContractSerializer. In order to opt-out, you have to go with private members. This wasn't the case before .NET 3.5 where only members decorated with [DataMemeber] are serialized.
More on what's new in .NET 3.5 SP1
Blog.
O
that's not true try to take a look at this code from msdn and try to uncomment and comment the datamember attribute in class person for the property LastName for example an yot will see that's not serialized as #Nair saied . I think that you are trying to write to the same file but the file it's locked so you will think that all properties are serialized. try to change the name every time and you will see that property not marked with datamember attribute will not be serialized
using System;
using System.Collections;
using System.IO;
using System.Runtime.Serialization;
using System.Xml;
// You must apply a DataContractAttribute or SerializableAttribute
// to a class to have it serialized by the DataContractSerializer.
[DataContract()]
class Person : IExtensibleDataObject
{
private string LastNameValue;
// Apply the DataMemberAttribute to fields (or properties)
// that must be serialized.
[DataMember()]
public string FirstName;
//[DataMember()]
public string LastName
{
get { return LastNameValue; }
set { LastNameValue = value; }
}
[DataMember(Name = "ID")]
public int IdNumber;
// Note that you can apply the DataMemberAttribute to
// a private field as well.
[DataMember]
private string Secret;
public Person(string newfName, string newLName, int newIdNumber)
{
FirstName = newfName;
LastName = newLName;
IdNumber = newIdNumber;
Secret = newfName + newLName + newIdNumber;
}
// The extensionDataValue field holds data from future versions
// of the type. This enables this type to be compatible with
// future versions. The field is required to implement the
// IExtensibleDataObject interface.
private ExtensionDataObject extensionDatavalue;
public ExtensionDataObject ExtensionData
{
get
{
return extensionDatavalue;
}
set
{
extensionDatavalue = value;
}
}
}
public class Test
{
public static void Main(string[] args)
{
try
{
WriteObject(#"DataMemberAttributeExample.xml");
ReadObject(#"DataMemberAttributeExample.xml");
}
catch (Exception exc)
{
Console.WriteLine(
"The serialization operation failed: {0} StackTrace: {1}",
exc.Message, exc.StackTrace);
}
finally
{
Console.WriteLine("Press <Enter> to exit....");
Console.ReadLine();
}
}
public static void WriteObject(string filename)
{
// Create a new instance of the Person class.
Person p1 = new Person("Zighetti", "Barbara", 101);
FileStream writer = new FileStream(filename,
FileMode.OpenOrCreate);
DataContractSerializer ser =
new DataContractSerializer(typeof(Person));
ser.WriteObject(writer, p1);
writer.Close();
}
public static void ReadObject(string filename)
{
// Deserialize an instance of the Person class
// from an XML file.
FileStream fs = new FileStream(filename,
FileMode.OpenOrCreate);
DataContractSerializer ser =
new DataContractSerializer(typeof(Person));
// Deserialize the data and read it from the instance.
Person deserializedPerson = (Person)ser.ReadObject(fs);
fs.Close();
Console.WriteLine(String.Format("{0} {1}, ID: {2}",
deserializedPerson.FirstName, deserializedPerson.LastName,
deserializedPerson.IdNumber));
}
}
I've got some serialisation code set up as follows:
static void SerialiseObject(Object o, String path)
{
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream(path, FileMode.Create);
formatter.Serialize(stream, o);
stream.Close();
}
static Object DeserialiseObject(String path)
{
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream(path, FileMode.Open, FileAccess.Read);
Object o = (Object)formatter.Deserialize(stream);
stream.Close();
return o;
}
And a class with the following member defined:
[Serializable]
public class CircuitModel
{
public Dictionary<String, Bus> Buses { protected set; get; }
...
}
I populate the Dictionary, and then the following code successfully serialises and deserialises the dictionary, with all Bus objects intact:
SerialiseObject(CircuitModel.Buses, "temp.bin");
Object o = DeserialiseObject("temp.bin");
But when I try to do the same for CircuitModel:
SerialiseObject(CircuitModel, "temp.bin");
Object o = DeserialiseObject("temp.bin");
CircuitModel.Buses has been initialised, but is empty.
I've also tried implementing serialisation with ISerializable (for the Bus and CircuitModel classes) and had exactly the same problem
Any idea as to why this would be happening?
I think you have something more sinister going on with your child collection because binary serialization of Dictionaries within classes does work just fine.
[TestFixture]
public class SerializeTest
{
[Test]
public void TestSer()
{
var parent = new Parent
{
Name = "Test"
};
parent.Children.Add("Child1", new Child {Name = "Child1"});
parent.Children.Add( "Child2", new Child { Name = "Child2" } );
SerialiseObject(parent, "test.bin");
var copy = DeserialiseObject("test.bin") as Parent;
Assert.IsNotNull(copy);
Assert.AreEqual(2, copy.Children.Count);
Assert.IsTrue(copy.Children.ContainsKey("Child1"));
Assert.AreEqual("Child1", copy.Children["Child1"].Name);
}
static void SerialiseObject( Object o, String path )
{
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream( path, FileMode.Create );
formatter.Serialize( stream, o );
stream.Close();
}
static Object DeserialiseObject( String path )
{
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream( path, FileMode.Open, FileAccess.Read );
Object o = (Object) formatter.Deserialize( stream );
stream.Close();
return o;
}
[Serializable]
private class Parent
{
public string Name { get; set; }
public Dictionary<string, Child> Children { get; protected set; }
public Parent()
{
Children = new Dictionary<string, Child>();
}
}
[Serializable]
private class Child
{
public string Name { get; set; }
}
}
The children deserialize with the parent and contain the details they were initialized with. I would check any code that is setting your Buses collection. My example just did it in the constructor of the parent class, but it may be possible that you have rogue code setting it after it's been deserialized?
Dictionaries are not serializable. Remove the dictionary if you need to serialize that data, and replace it by a list of a custom class that contains the data in the dictionary:
[Serializable]
public class BusItem
{
public string Name {get;set;}
public Bus Bus {get;set;}
}
Edit: I just found out you can actually serialize Dictionaries using the DataContractSerializer instead.
http://theburningmonk.com/2010/05/net-tips-xml-serialize-or-deserialize-dictionary-in-csharp/
If you are talking about XML serialization, it might be because Dictionary is not serializable to XML. Look at Why isn't there an XML-serializable dictionary in .NET.
I want to converts objects to xml and reverse. I can serialize my objects without any problems to an xml document using this method:
public static void SaveObjectToXML(T _obj, string fileName)
{
XmlSerializer ser = new XmlSerializer(typeof(T));
FileStream str = new FileStream(fileName, FileMode.Create);
ser.Serialize(str, _obj);
str.Close();
}
But with the Deserializer I've got some problems... While the process I get no Errors or problems (same for calling methods of it) but when I try do acess any members the problem begins. All members are null (same for methods acessing any members). Heres the code:
public static T SaveXMLToObject(string fileName)
{
XmlSerializer ser = new XmlSerializer(typeof(T));
StreamReader sr = new StreamReader(fileName);
T dataSet = (T)ser.Deserialize(sr);
return dataSet;
}
Any Ideas?
edit:
OK I just added the using Statement, thanks for that :)
The complete classes are a bit to much, but they look like this:
public class User
{
private string _name;
public string Name
{
get { return _name; }
set { }
}
}
public class AllUser
{
private User[] _users;
public User[] Users
{
get { return _users; }
set { }
}
}
Assuming sample code is complete I am not surprised at all. You have empty setters (which is what serialization will use). Don't just satisfy serialization error by adding empty setter. It is required for populating your data.
Changes that to
set { _users = value; }
and it should work
I think you just need to mark the classes you are deserializing to as [Serializable]. For example:
[Serializable]
public class User
{
...
}