If you want to serialize this as a set of simple KeyValuePairs, you can use custom Struct for this. Unfortunately, the built-in KeyValuePair generator will not 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 can also successfully read this XML back into the object and print the information.
You can check this for yourself in the 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); } } }
source share