How do I serialize serialiable data in my class that uses IXmlSerializable?
I have a class the implements IXmlSerializable
like below:
public class SomeClass : IXmlSerializable
{
public SomeSerializableClass ClassA { get; set; }
public SomeNonSerializableClass ClassB { get; set; }
public void ReadXml(XmlReader reader)
{
reader.ReadStartElement("RootElement");
do
{
if (reader.Name == "SomeNonSerializableClass")
开发者_如何学编程 {
// Perform custom serialization
}
else if (reader.Name == "SomeSerializableClass")
{
// I just want to use the SomeSerializableClass's
// already implemented serialization process here.
}
}
while (reader.Name != "RootElement");
reader.ReadEndElement();
}
}
Let's just look at the ReadXml
implementation for this example. I have two classes, one is name SomeNonSerializableClass
, which is why the SomeClass
class has IXmlSerializable
implemented. I then also have the SomeSerializableClass
, which can be serialized natively, using XmlSerializer
for example.
I'm serializing SomeClass
using XmlSerializer
, and I could manually serialize SomeSerializableClass
, but why would I if it already can be serialized using .NETs serialization classes? So how can I just serialize it and pass it into the reader/writer?
You can use XmlSerializer
for that type. Something like:
public void ReadXml(XmlReader reader)
{
reader.ReadStartElement("SomeClass");
do
{
if (reader.Name == "ClassB")
{
reader.ReadStartElement();
// manually deserialize SomeNonSerializableClass here
reader.ReadEndElement();
}
else if (reader.Name == "ClassA")
{
reader.ReadStartElement();
var serializer = new XmlSerializer(typeof(SomeSerializableClass));
ClassA = (SomeSerializableClass)serializer.Deserialize(reader);
reader.ReadEndElement();
}
}
while (reader.Name != "SomeClass");
reader.ReadEndElement();
}
public void WriteXml(XmlWriter writer)
{
writer.WriteStartElement("ClassB");
// manually serialize SomeNonSerializableClass here
writer.WriteEndElement();
writer.WriteStartElement("ClassA");
var serializer = new XmlSerializer(typeof(SomeSerializableClass));
serializer.Serialize(writer, ClassA);
writer.WriteEndElement();
}
精彩评论