【发布时间】:2018-09-06 14:39:10
【问题描述】:
我想创建一个如下结构的 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"));
【问题讨论】:
-
您的代码中没有
List,您能否将实际导致错误的代码包含在内? -
我没有提到我正在初始化 Color 类并从字典中传递值: public Fruit(string fruitname, Dictionary
colorDictionary) { FruitName = fruitname; foreach (KeyValuePair entry in colorDictionary) { c = new Color(entry.Key, entry.Value); } -
您可以编辑问题以包含此内容吗?并且还包括引发异常的位,因为它不会是那个代码。我们需要minimal reproducible example 才能提供帮助。
-
在网络上搜索尝试序列化字典。您会发现很多热门歌曲。
-
我根据您输入的代码进行了一些假设以修复格式。但是,仍然不清楚您在
Fruit构造函数中正在做什么(因为它会遍历字典并多次设置相同的属性),或者Fruits是什么,也不清楚之后您对serializer做了什么最后一行。
标签: c# xml serialization