Я хочу создать XML-документ в следующей структуре:
<Fruits>
<Fruit>
<FruitName>Apple</FruitName>
<Color>
<Color1>Green</Color1>
<Color2>Green</Color2>
</Color>
</Fruit>
<Fruit>
<FruitName>Lemon</FruitName>
<Color>
<Color1>Green</Color1>
<Color2>Yellow</Color2>
</Color>
</Fruit>
<Fruit>
<FruitName>Orange</FruitName>
<Color Value="Orange">
</Color>
</Fruit>
</Fruits>
У меня есть класс:
[Serializable()]
public class Fruit
{
[XmlElement(ElementName = "FruitName", Order = 1)]
public string "FruitName", { get; set; }
[XmlElement(ElementName = "Color", Order = 2)]
public Color c =new Color();
public Fruit(string fruitname, Dictionary<string, string> colorDictionary)
{
//constructor to set values for fruitname and dictionary as received from the calling class
fruitName = fruitname;
foreach (KeyValuePair<string, string> entry in colorDictionary)
{
c = new Color(entry.Key, entry.Value);
}
}
}
public class Color
{
[XmlElement(ElementName = "Color1", IsNullable = true)]
public string Color1 { get; set; }
[XmlElement(ElementName = "Color2", IsNullable = true)]
public string Color2 { get; set; }
[XmlAttribute("Value")]
public string Value { get; set; }
/// <summary>
/// Parameterless constructor for serialization.
/// </summary>
public Color() { }
/// <summary>
/// Parameterized constructor for getting and setting values.
/// </summary>
public Color(string col1, string Col2)
{
Color1 = col1;
Color2 = col2;
}
}
Я не понимаю, но в коде есть какая-то проблема, но я не могу найти то, что, поскольку я не могу сериализоваться. Я получаю сообщение об ошибке:
System.InvalidOperationException: при отображении типа 'System.Collections.Generic.List`1
произошла ошибка.
Fruit f = new Fruit(fruitName, colorDictionary);
Fruits.Add(fruit);
XmlSerializer serializer = new XmlSerializer(typeof(List<Fruit>), new XmlRootAttribute("Fruits"));