views:

63

answers:

1

I have a serialization utility that serializes an object to an XDocument. It works quite well :

public static class SerializationUtil
{
    public static T Deserialize<T>(XDocument doc)
    {
        XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));

        using (var reader = doc.Root.CreateReader())
        {
            return (T)xmlSerializer.Deserialize(reader);
        }
    }

    public static XDocument Serialize<T>(T value)
    {
        XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));

        XDocument doc = new XDocument(z);
        using (var writer = doc.CreateWriter())
        {
            xmlSerializer.Serialize(writer, value);
        }

        return doc;
    }

Been using it quite happily and suddenly I get :

There was an error generating the XML document.

The inner exception is :

This XmlWriter does not support base64 encoded data.

Turns out that the XDocument.CreateWriter() instance method gives you a writer of type System.Xml.XmlWellFormedWriter, and that that writer can't write base64 encoded data (my object contains a byte[]).

MSDN doesn't even seem to mention this class - but I can't seem to create any other type of writer from XDocument.

I could just serialize to a string, but i was trying to be clever and avoid using any hacks. Any way to serialize to XDocument when base64 is needed for certain fields.

+1  A: 

According to the docs, there's no allowance for bytes. A surrogate base64 encoded string property is probably your best bet (is it a hack if its by design?).

Nader Shirazie
ah ok - i just assumed any valid XML could be supported. i just wish the XmlSerializer was cleverer enough to handle it for me. i'll just revert back to serializing to a StringWriter which works fine
Simon_Weaver
@nader but shouldnt the xmlserializer be responsible for the conversion? after all xml is all just text anyway.
Simon_Weaver
The serializer _is_ converting it, but the `XmlWriter` from the `XDocument` doesn't like its conversion -- that's the error you're getting. There may be other XmlWriters that don't have the same problem -- for example, instead of using an `System.Xml.Linq.XDocument`, you might have better luck with using `System.Xml.XmlDocument`.
Nader Shirazie
Alternatively, you have to work around the restrictions, by restricting your type to only have properties that work well... which, in this case, means not serializing the byte array directly.
Nader Shirazie