Reputation: 7391
I need to deserialize the following XML into a C# class:
<NodeConfiguration>
<DBChange value="2022"/>
<DBChange value="555" />
<DBChange value="12:00" />
</NodeConfiguration>
To do this I constructed the following classes:
[XmlType("NodeConfiguration")]
public class NodeConfigurationSerialize
{
public NodeConfigurationSerialize()
{
}
[XmlElement("DBChange")]
public DBChange[] ChangeList { get; set; }
}
And:
public class DBChange : StringSerializable<DBChange>, IEquatable<DBChange>, IXmlSerializable
{
private string mValue;
public string Value
{
get { return mValue; }
set { mValue = value; }
}
public void ReadXml(System.Xml.XmlReader reader)
{
mValue = reader.GetAttribute("value");
}
public void WriteXml(System.Xml.XmlWriter writer)
{
writer.WriteAttributeString("value", mValue);
}
}
The problem is that whenever I try to deserialize this class using the method:
Deserialize<NodeConfigurationSerialize>(xml, null);
I get a invalid XML error.
How should I write my DBChange and NodeConfigurationSerialize classes so that I can successfully deserialize them from the XML above?
PS: I am using Visual Studio 2010 and .NET Framework 4.0
EDIT 1:
I've changed my NodeConfigurationSerialize class to:
[XmlType("NodeConfiguration")]
public class NodeConfigurationSerialize
{
public NodeConfigurationSerialize()
{
ChangeList = new List<DBChange>();
}
[XmlElement("DBChange")]
public List<DBChange> ChangeList { get; set; }
}
And I've also done as @woni suggested and added the reader.Read(); to my DBChange class' ReadXml method. After that everything worked fine!
Thank you all for your answers!
Upvotes: 1
Views: 686
Reputation: 11955
If your not stuck on using XmlSerialize and NodeConfiguration is your root node and using these extensions you could write it like so:
public class NodeConfiguration
{
XElement self;
public NodeConfiguration(XElement self) { this.self = self; }
public IEnumerable<string> DBChanges
{
get
{
return self.GetEnumerable("DBChange", x => x.Get("value", string.Empty));
}
}
}
You would use it like:
XElement root = XElement.Load("filepath");
NodeConfiguration config = new NodeConfiguration(root);
foreach(string dbchange in config.DBChanges)
{
// ...
}
Upvotes: 0
Reputation: 5795
I have verified your example code and you are getting an InnerException of type System.OutOfMemoryException.
The Method ReadXml of DBChange class is called in an infinite loop.
Change this method to the following:
public void ReadXml(System.Xml.XmlReader reader) {
mValue = reader.GetAttribute("value");
reader.Read();
}
The call of reader.Read() will tell the XmlSerializer to finish reading of the current element and go to the next element in XML-Sequence.
Upvotes: 2
Reputation: 3877
Ensure you have this in the file:
<?xml version="1.0" encoding="ISO-8859-1"?>
<NodeConfiguration>
<DBChange value="2022"/>
<DBChange value="555" />
<DBChange value="12:00" />
</NodeConfiguration>
Change:
[XmlType("NodeConfiguration")]
To:
[XmlRoot("NodeConfiguration")]
Upvotes: 0