【问题标题】:Different behavior in XmlSerializer with/without XmlElement带有/不带有 XmlElement 的 XmlSerializer 中的不同行为
【发布时间】:2012-01-04 13:14:47
【问题描述】:
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Serialization;
using System.Linq;

namespace Serialize
{    
    public class Good
    {
        public int a;
        public Good() {}

        public Good(int x)
        {
            a = x;
        }
    }

    public class Hello
    {
        public int x;
        public List<Good> goods = new List<Good>();

        public Hello()
        {
            goods.Add(new Good(1));
            goods.Add(new Good(2));
        }
    }

    [XmlRootAttribute("Component", IsNullable = false)]
    public class Component {
        //[XmlElement("worlds_wola", IsNullable = false)]
        public List<Hello> worlds;      

        public Component()
        {
            worlds = new List<Hello>() {new Hello(), new Hello()}; 
        }
    }

    class Cov2xml
    {
        static void Main(string[] args)
        {
            string xmlFileName = "ip-xact.xml";
            Component comp = new Component();

            TextWriter writeFileStream = new StreamWriter(xmlFileName);

            var ser = new XmlSerializer(typeof(Component));
            ser.Serialize(writeFileStream, comp);
            writeFileStream.Close();

        }
    }
}

通过这个 XmlSerializer 代码,我得到了这个 XML 文件。

我只有一个“世界”元素,它有两个 Hello 元素。

但是,当我在世界变量之前添加 XmlElement 时。

[XmlElement("worlds_wola", IsNullable = false)]
public List<Hello> worlds

我有两个 worlds_wola 元素而不是一个。

这是为什么?如何使用 XmlElement 指定标签的名称,但只有一个“worlds_wola”元素,如下所示?

<worlds_wola>
  <Hello>
   ...
  </Hello>
  <Hello>
   ...
  </Hello>
</worlds_wola>

【问题讨论】:

  • WAG:尝试改用 XmlArrayAttribute。

标签: c# xml xml-serialization


【解决方案1】:

您需要为您的集合使用XmlArrayAttribute 而不是 XmlElementAttribute。

【讨论】:

    【解决方案2】:

    根据查尔斯的回答,我发现这正是我想要的。

    [XmlArray("fileSet")]
    [XmlArrayItem(ElementName = "file", IsNullable = false)]
    public List<Hello> worlds;   
    

    通过这个设置,我可以得到

    <fileSet>
        <file>...</file>
    

    代替

    <worlds>
        <Hello>...</Hello>
    

    【讨论】:

      猜你喜欢
      • 2012-12-25
      • 2013-07-21
      • 1970-01-01
      • 2012-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-19
      相关资源
      最近更新 更多