Serializing Class Derived from Generic Collection yet Deserializing the Generic Collection

Posted by Stacey on Stack Overflow See other posts from Stack Overflow or by Stacey
Published on 2010-03-14T04:19:42Z Indexed on 2010/03/14 6:35 UTC
Read the original article Hit count: 424

Filed under:
|

I have a Repository Class with the following method...

public T Single<T>(Predicate<T> expression)
{
    using (var list = (Models.Collectable<T>)System.Xml.Serializer.Deserialize(typeof(Models.Collectable<T>), FileName))
    {
        return list.Find(expression);
    }
}

Where Collectable is defined..

[Serializable]
public class Collectable<T> : List<T>, IDisposable
{
    public Collectable() { }

    public void Dispose() { }
}

And an Item that uses it is defined..

[Serializable]
[System.Xml.Serialization.XmlRoot("Titles")]
public partial class Titles : Collectable<Title>
{
}

The problem is when I call the method, it expects "Collectable" to be the XmlRoot, but the XmlRoot is "Titles" (all of object Title).

I have several classes that are collected in .xml files like this, but it seems pointless to rewrite the basic methods for loading each up when the generic accessors do it - but how can I enforce the proper root name for each file without hard coding methods for each one? The [System.Xml.Serialization.XmlRoot] seems to be ignored.

When called like this...

var titles = Repository.List<Models.Title>(); 

I get the exception

<Titlesxmlns=''> was not expected. 

The XML is formatted such as. ..

<?xml version="1.0" encoding="utf-16"?>
<Titles xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <Title>
        <Id>442daf7d-193c-4da8-be0b-417cec9dc1c5</Id>
    </Title>
</Titles>

Here is the deserialization code.

  public static T Deserialize<T>(String xmlString)
    {
        System.Xml.Serialization.XmlSerializer XmlFormatSerializer
            = new System.Xml.Serialization.XmlSerializer(typeof(T));

        StreamReader XmlStringReader = new StreamReader(xmlString);

        //XmlTextReader XmlFormatReader = new XmlTextReader(XmlStringReader);

        try
        {
            return (T)XmlFormatSerializer.Deserialize(XmlStringReader);
        }
        catch (Exception e)
        {
            throw e;
        }
        finally
        {
            XmlStringReader.Close();
        }
    }

© Stack Overflow or respective owner

Related posts about c#

Related posts about xml-serialization