Reputation: 1776
So basically I have 2 classes:
public class Configuration
{
public Configuration()
{
Sections = new List<Section>();
}
public List<Section> Sections { get; private set; }
}
public class Section : 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);
}
}
This code works well:
var configuration = new Configuration();
configuration.Sections.Add(new Section {Name = "#Submitter.LoginTest"});
configuration.Sections.Add(new Section {Name = "Default"});
using (StreamWriter writer = new StreamWriter(@"d:\data.xml"))
{
XmlSerializer x = new XmlSerializer(typeof(Configuration));
x.Serialize(writer, configuration, XmlSerializerHelper.EmptyNamespaces);
}
Serialization result:
<?xml version="1.0" encoding="utf-8"?>
<Configuration>
<Sections>
<Section Name="#Submitter.LoginTest" />
<Section Name="Default" />
</Sections>
</Configuration>
But this code throws an Exception: An unhandled exception of type 'System.InvalidOperationException' occurred in System.Xml.dll Additional information: There is an error in XML document (4, 6).
var configuration = new Configuration();
using (StreamReader reader = new StreamReader(@"d:\data.xml"))
{
XmlSerializer x = new XmlSerializer(typeof(Configuration));
configuration = (Configuration) x.Deserialize(reader);
}
So for serialization of Section I can't use attribute-based serialization, but it works perfectly fine:
public class Section
{
[XmlAttribute]
public string Name { get; set; }
}
UPD1: Serialization/deserialization of Section as root works well
Upvotes: 0
Views: 1225
Reputation: 488
It is because the reader does not move to the next node while deserializing in the class Section
and repeatedly tries to read the same node eventually leading to OutofMemory exception. You should point the reader to next node after reading the attribute. There may be other ways of solving this issue but this should resolve your issue at the moment.
public void ReadXml(XmlReader reader)
{
Name = reader.GetAttribute("Name");
reader.Read();
}
Upvotes: 2