C
C#2y ago
Sparky

❔ Is there an easy way to serialize a Dictionary<string, string> to XML nodes?

I'm writing a program that has to produce the following XML:
<Attributes>
<Color>red</Color>
<Size>small</Size>
<Material>plastic</Material>
</Attributes>
<Attributes>
<Color>red</Color>
<Size>small</Size>
<Material>plastic</Material>
</Attributes>
I'm trying to figure out the best data model that can be serialized to something like this. The most obvious choice seems to be a Dictionary<string, string>, but I can also use a custom class with two properties (Name, Value). I've seen some solutions on stack overflow, but all of them involve creating a bunch of helper classes and writing hundreds of lines of additional code, and I refuse to believe that there is no simpler way of doing this, with Xml attributes or something like that.
5 Replies
Angius
Angius2y ago
Generally speaking, XML is a bitch Surprisingly so, seeing how fond of it Microsoft is
Sparky
Sparky2y ago
Oh yeah. I'm currently trying to write a IXmlSerializable to see if I can get it to work.. Yeah, I think I solved it.
public class MyAttribute : IXmlSerializable {

public string Key { get; set; }
public string Value { get; set; }

public XmlSchema GetSchema() => null;

public void WriteXml(XmlWriter writer)
{
writer.WriteElementString(Key, null, Value);
}

public void ReadXml(XmlReader reader)
{
}
}
public class MyAttribute : IXmlSerializable {

public string Key { get; set; }
public string Value { get; set; }

public XmlSchema GetSchema() => null;

public void WriteXml(XmlWriter writer)
{
writer.WriteElementString(Key, null, Value);
}

public void ReadXml(XmlReader reader)
{
}
}
Angius
Angius2y ago
Jesus, the more I read about XML serialization the more I hate it Why does the serializer use typeof instead of being generic? Why does it insert data into a stream? Who designed this shit...? That said... this works
var s = new XmlSerializer(typeof(Root));
s.Serialize(Console.Out, new Root
{
Attributes = new Attributes
{
Color = "red",
Size = "small",
Material = "denim"
}
});

public class Root
{
public Attributes Attributes { get; set; }
}

public class Attributes
{
public string Color { get; set; }
public string Size { get; set; }
public string Material { get; set; }
}
var s = new XmlSerializer(typeof(Root));
s.Serialize(Console.Out, new Root
{
Attributes = new Attributes
{
Color = "red",
Size = "small",
Material = "denim"
}
});

public class Root
{
public Attributes Attributes { get; set; }
}

public class Attributes
{
public string Color { get; set; }
public string Size { get; set; }
public string Material { get; set; }
}
Angius
Angius2y ago
Kinda
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server
More Posts