If you wanted to serialize this as a set of simple KeyValuePairs you could use a custom Struct to accomplish this. Unfortunately the built in generic KeyValuePair won't work.
But, given the following class definitions:
[XmlRoot("Books")]
public class BookList
{
[XmlElement("Book")]
public List<Book> Books { get; set; }
}
public class Book
{
[XmlAttribute("Title")]
public string Title { get; set; }
[XmlElement("Attribute")]
public List<AttributePair<String, String>> Attributes { get; set; }
}
[Serializable]
[XmlType(TypeName = "Attribute")]
public struct AttributePair<K, V>
{
public K Key { get; set; }
public V Value { get; set; }
public AttributePair(K key, V val)
: this()
{
Key = key;
Value = val;
}
}
When I serialize an object using this information I get an XML structure that looks something like this.
<?xml version="1.0"?>
<Books xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Book Title="To win a woman">
<Attribute>
<Key>Author</Key>
<Value>Bob</Value>
</Attribute>
<Attribute>
<Key>Publish Date</Key>
<Value>1934</Value>
</Attribute>
<Attribute>
<Key>Genre</Key>
<Value>Romance</Value>
</Attribute>
</Book>
</Books>
I am also able to successfully read that XML right back into an object and print out the information.
You can test it out for yourself in a console application to see the results.
using(var file = File.OpenRead("booklist.xml"))
{
var readBookCollection = (BookList)serializer.Deserialize(file);
foreach (var book in readBookCollection.Books)
{
Console.WriteLine("Title: {0}", book.Title);
foreach (var attributePair in book.Attributes)
{
Console.CursorLeft = 3;
Console.WriteLine("Key: {0}, Value: {1}",
attributePair.Key,
attributePair.Value);
}
}
}