【问题标题】:XML Serialization in C# for nested nodesC# 中用于嵌套节点的 XML 序列化
【发布时间】: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


【解决方案1】:

我想Fruit 也应该有无参数构造函数。考虑以下示例:

public static void Main(string[] args)
{
    string appleName = "Apple";
    Dictionary<string, string> appleColors = new Dictionary<string, string>
    {
        { "Green", "Green" }
    };
    string lemonName = "Lemon";
    Dictionary<string, string> lemonColors = new Dictionary<string, string>
    {
        { "Green", "Yellow" }
    };
    string orangeName = "Orange";
    Dictionary<string, string> orangeColors = new Dictionary<string, string>
    {
        { "Orange", "Orange" }
    };

    var fruits = new List<Fruit>();
    Fruit apple = new Fruit(appleName, appleColors);
    Fruit lemon = new Fruit(lemonName, lemonColors);
    Fruit orange = new Fruit(orangeName, orangeColors);
    fruits.Add(apple);
    fruits.Add(lemon);
    fruits.Add(orange);

    XmlSerializer serializer = new XmlSerializer(typeof(List<Fruit>), new XmlRootAttribute("Fruits"));
    using (var stream = new FileStream("fruits.xml", FileMode.CreateNew))
    {
        using(var wr = new StreamWriter(stream))
        {
            serializer.Serialize(wr, fruits);
        }
    }

    Console.ReadKey();
}

[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()
    {

    }

    public Fruit(string fruitname, Dictionary<string, string> colorDictionary)
    {
        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>
    /// <param name="torque"></param>
    public Color(string col1, string col2)
    {
        Color1 = col1;
        Color2 = col2;
    }
}

希望对你有帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-05
    • 1970-01-01
    • 2016-06-30
    • 2016-01-14
    • 1970-01-01
    • 2015-05-22
    • 1970-01-01
    相关资源
    最近更新 更多