简体   繁体   中英

Deserializing IXmlSerializable struct hierarchy

I have the following scenario:

public struct Foo : IXmlSerializable
{
    public Bar bar;
}

public struct Bar : IXmlSerializable
{
}

I would like to be able to serialize/deserialize Foo from XML. The WriteXml method is very easy to implement:

public void WriteXml(XmlWriter writer)
{
    writer.WriteStartElement("bar");
    this.bar.WriteXml(writer);
    writer.WriteEndElement();
}

But I'm lost at how to write the ReadXml method.

public void ReadXml(XmlReader reader)
{
    reader.MoveToContent();

    ????

    reader.ReadEndElement();
}

Firstly, do I need to instantiate a new instance of Bar to call ReadXml on?

Secondly, how can I write my ReadXml methods so that they "stack"? I want to be able to pass my reader to a child without worrying about it coming back in an innapropriate state.

Thanks

Your WriteXml method in Foo is not implemented correctly. You should call XmlSerializer to serialize the Bar instance instead of calling its WriteXml manually:

public void WriteXml(XmlWriter writer)
{
    writer.WriteStartElement("bar");
    new XmlSerializer(typeof(Bar)).Serialize(writer, bar);
    writer.WriteEndElement();
}

Firstly, do I need to instantiate a new instance of Bar to call ReadXml on?

No. Instead, use XmlSerializer and call its Deserialize method analogously to the serialization example above.

Secondly, how can I write my ReadXml methods so that they "stack"? I want to be able to pass my reader to a child without worrying about it coming back in an innapropriate state.

Yes. It works that way by default. You don't have to do anything special to maintain state but pass the reader / writer instance. Just use XmlSerializer recursively to (de)serialize nested complex objects.

Note: There's a nice tutorial here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM