0

Hello i have another question. First of all i have following classes:

 {
        [DataMember]
[XmlElement(ElementName = "RecipeBook")]
public Dictionary<string, Recipe> DRezeptbuch = new Dictionary<string, Recipe>(); 
}

    public class Recipe
{
    [XmlElement(ElementName = "Name")]
    public string Name { get; set; }

    [XmlElement(ElementName = "Size")]
    public int? Size { get; set; }

    [XmlElement(ElementName = "Ingredients")]
    public List<Ingredient> Ingredients { get; set; }
}

    public class Ingredient
{
    [XmlElement(ElementName = "Name")]
    public string Name { get; set; }

    [XmlElement(ElementName = "Amount")]
    public decimal amount;

    [XmlElement(ElementName = "Unit")]
    public Units.Unit unit;

    [XmlElement(ElementName = "Specification")]
    public List<Units.Specification> specification;

    [XmlElement(ElementName = "Category")]
    public Units.Category category;
}

So im filling the "DRezeptbuch" and want to write this to a file. I tried xmlserialization but i failed.

            //var serializer = new XmlSerializer(dRezeptbuch.GetType());
        //using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
        //{
        //    serializer.Serialize(ms, dRezeptbuch);
        //    ms.Position = 0;
        //    xmlDoc.Load(ms);
        //    return xmlDoc.InnerXml;
        //}

Then i tried it with this DataContract thingy but i wont work either.

            var serializer = new DataContractSerializer(typeof(RecipeBook));
        string xmlString;
        using (var sw = new StringWriter())
        {
            using (var writer = new XmlTextWriter(sw))
            {
                writer.Formatting = Formatting.Indented; // indent the Xml so it's human readable
                serializer.WriteObject(writer, dRezeptbuch);
                writer.Flush();
                xmlString = sw.ToString();

            }
        }

so what should i do? is there a good way to save this dictionary?

Michael
  • 39
  • 6
  • https://stackoverflow.com/a/4123648/1390548 does this help – Jawad Dec 14 '19 at 16:02
  • No, cause its says i cant use Dictionaries.. therefore i have to use DataContract.. and that didnt work. – Michael Dec 14 '19 at 16:04
  • What does your `RecipeBook` class definition look like? You left the line with the class type out of the code you posted. – quaabaam Dec 14 '19 at 16:33
  • 1
    What do you mean by `didn't work`? What issue did you face? – Chetan Dec 14 '19 at 17:19
  • Unless you really have to have the `Dictionary` serialized I would instead consider serializing your `Dictionary` as a `List` and then map that to a `Dictionary` on load. The `Recipe.Name` field seems like a reasonable field to use as the `Dictionary` key when loading. – quaabaam Dec 14 '19 at 19:00
  • any reason you are using xml instead of json? Try https://www.newtonsoft.com/json to serialize to json. – tubakaya Dec 14 '19 at 19:39

0 Answers0