for our software I've to change the xml serialization for on entiy of our project.
After a couple of hours I've found, that you can modify the xml serialization if you implement the interface IXmlSerializable
.
After some reading about how to implement this interface correctly, I've implemented this into the entity.
The entity which is implementing this interface is a child class. The parent class will be serialized into xml. If the child class is just a normal property, the serialization is correct and works like a charm. But if the parent class has a list of this child classes, the serialization ends into an endless loop.
Here's a very simple example to illustrate my problem:
public class ParentEntity
{
public List<ChildEntity> Childs { get; set; } = new List<ChildEntity>();
}
public class ChildEntity: IXmlSerializable
{
public string Name { get; set; }
public XmlSchema GetSchema()
{
return null;
}
public void ReadXml(XmlReader reader)
{
Name = reader.GetAttribute("Name");
}
public void WriteXml(XmlWriter writer)
{
writer.WriteAttributeString("Name", Name);
}
}
And this is the logik I'm using for the serialization
using (var memoryStream = new MemoryStream())
{
var serializer = new XmlSerializer(typeof(ParentEntity));
serializer.Serialize(memoryStream, parentEntity);
memoryStream.Position = 0;
var deserializedParentEntity = serializer.Deserialize(memoryStream) as ParentEntity;
Console.Read();
}
The object parentEntity
has been initialized correctly.
Then I'm serializing the object into xml.
After this, I'm deserializing the xml back into an object (Just for the showcase).
And here is my problem. The method ReadXml()
get called very very often. It looks like a endless loop. The end of the deserialization process I've never reached.
Has anyone an idea what my problem is?