How to serialize an object collection / dictionary into <key>value</key>
See the question and my original answer on StackOverflowI don't think you can do what you want with the very "static" XmlSerializer. Here are a couple of helpers that you could get you started with a dictionary (generic or not):
public static string Serialize(IDictionary dictionary)
{
using (StringWriter writer = new StringWriter())
{
Serialize(writer, dictionary);
return writer.ToString();
}
}
public static void Serialize(TextWriter writer, IDictionary dictionary)
{
if (writer == null)
throw new ArgumentNullException("writer");
using (XmlTextWriter xwriter = new XmlTextWriter(writer))
{
Serialize(xwriter, dictionary);
}
}
public static void Serialize(XmlWriter writer, IDictionary dictionary)
{
if (writer == null)
throw new ArgumentNullException("writer");
if (dictionary == null)
throw new ArgumentNullException("dictionary");
foreach (DictionaryEntry entry in dictionary)
{
writer.WriteStartElement(string.Format("{0}", entry.Key));
writer.WriteValue(entry.Value);
writer.WriteEndElement();
}
}
With these helpers, the following code:
Dictionary<string, string> Identifiers = new Dictionary<string,string>
{
{ "somename", "somedescription"},
{ "anothername", "anotherdescription" }
};
Console.WriteLine(Serialize(Identifiers));
will output this:
<somename>somedescription</somename><anothername>anotherdescription</anothername>
You can adapt to your will.