views:

1371

answers:

4

Are any of the .NET generic collections marked as IXmlSerializable? I've tried List<T> and Collection<T> but neither work out of the box.

Before I roll my own collection<T>, list<T>, or dictionary<T> class, I thought I'd check to see whether Microsoft had included something that does this already. It seems like basic functionality.

EDIT: By "rolling my own" I mean creating a class that inherits from a generic collection class and also implements IXmlSerializable. Here's one example: http://www.codeproject.com/KB/XML/IXmlSerializable.aspx. And here's another example: http://weblogs.asp.net/pwelter34/archive/2006/05/03/444961.aspx.

I'm using the DataContractSerializer within a method whose signature looks like this:

public static Stream GetXmlStream(IXmlSerializable item)

The problem is that while there are many classes in the .NET framework that are serializable, not all of them have explicitly implement the IXmlSerializable interface.

+4  A: 

As far as I know, there aren't any. You could take a look at the attached link, though. I think you'll find it useful.

Serialize and deserialize objects as Xml using generic types in C# 2.0

noroom
This article you linked to shows how to use generics to perform serialization. I want a generic collection that can be serialized.
dthrasher
A: 

After some further research on my own, I came to the same conclusion. None of the .NET generic collections are IXmlSerializable as of .NET 3.5 SP1.

dthrasher
+3  A: 

There is no requirement to implement IXmlSerializable to be xml serializable.

public class Foo 
{
    public List<string> Names { get; set; }
}

will xml serialize just fine producing something like:

<?xml version="1.0" encoding="utf-16"?>
<Foo 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt;
  <Names>
    <string>a</string>
    <string>b</string>
    <string>c</string>
  </Names>
</Foo>

whereas

public class Foo<T> 
{
    public List<T> Names {  get; set; }
}

will produce

<?xml version="1.0" encoding="utf-16"?>
<FooOfString 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt;
  <Names>
    <string>a</string>
    <string>b</string>
    <string>c</string>
  </Names>
</FooOfString>
ShuggyCoUk
+2  A: 

Related to your question, if you want to serialize/deserialize an IDictionary see this useful post. I'd use the pattern shown here for your read and write methods though, as they deal better with different situations.

Rory
That's a great link. I wound up doing something very similar. +1
dthrasher
Also see the second link i added. I had some problems with the code on the first one, particularly if the collection is empty...
Rory