views:

807

answers:

2

I need to be able to Xml Serialize a class which is internal, so I must implement IXmlSerializable.

This class has a two strings and a List in it.

I know to read and write the strings using WriteElementString & ReadElementContentAsString.

However, I'm lost on how to read & write the List in the ReadXml & WriteXml methods.

How do I do this, or is there a way to serialize and deserialize the object while maintaining it's internal accessibility?

+3  A: 

Just write a <List> element for the list itself, then loop over the items and write them out as <Item> elements.

If the elements are instances of a class that can be XML Serialized, then you could create an XmlSerializer instance for the type of the element, then just serialize each one to the same XmlWriter you're already using. Example:


public void WriteXml(XmlWriter writer)
{
    writer.WriteStartElement("XmlSerializable");

    writer.WriteElementString("Integer", Integer.ToString());

    writer.WriteStartElement("OtherList");
    writer.WriteAttributeString("count", OtherList.Count.ToString());

    var otherSer = new XmlSerializer(typeof(OtherClass));
    foreach (var other in OtherList)
    {
        otherSer.Serialize(writer, other);
    }
    writer.WriteEndElement();

    writer.WriteEndElement();
}

public void ReadXml(XmlReader reader)
{
    reader.ReadStartElement("XmlSerializable");

    reader.ReadStartElement("Integer");
    Integer = reader.ReadElementContentAsInt();
    reader.ReadEndElement();

    reader.ReadStartElement("OtherList");
    reader.MoveToAttribute("count");
    int count = int.Parse(reader.Value);

    var otherSer = new XmlSerializer(typeof (OtherClass));
    for (int i=0; i<count; i++)
    {
        var other = (OtherClass) otherSer.Deserialize(reader);
        OtherList.Add(other);
    }

    reader.ReadEndElement();
    reader.ReadEndElement();
}
John Saunders
List<> does not implement IXmlSerializable, it is serialize-able because of it's public access.I understand writing them like stated above, but how do I nest the Items in the list in code, and then how do I remove them from the nest later? Which methods should I be looking at to accomplish this?
Präriewolf
There are issues with the wrapper element in the code as sample here (http://www.codeproject.com/KB/XML/ImplementIXmlSerializable.aspx explains how to implement ReadXml and WriteXml correctly)
jdehaan
+2  A: 

You might find this link useful, I know I did Shifting Bits

Simon Wilson