【问题标题】:Naming a List<T> element for XML serialization为 XML 序列化命名 List<T> 元素
【发布时间】:2015-05-25 04:37:44
【问题描述】:

我正在尝试将一个类序列化为 XML,但对于属性只是一个列表的子元素,我无法获得我想要的结果。 (C#,.Net4.5,在 WinForms 中尝试)

我的例子如下:

[Serializable]
public class Model
{
    public string element = "elTest";
    public List<String> roles;
}

我将其写入 XML

    private void button2_Click(object sender, EventArgs e)
    {
        var me = new Model();
        me.roles = new List<string>()
        {
            "testString"
        };
        var ser = new XmlSerializer(typeof(OtherModel));
        using (var sw = new StreamWriter("C:\\temp\\test123.xml"))
        {
            ser.Serialize(sw, me);
        }
    }

这给了我这样的输出:

 <element>elTest</element>
  <roles>
    <string>testString</string>
  </roles>

我如何得到它,这样

<string>

在这个例子中显示为

<role>

我尝试使用自己的属性创建另一个类 Role 并创建一个 List,但后来我得到了类似的东西

  <roles>
    <Role>
      <myRole>theRole</myRole>

这不是我想要的。

谢谢。

【问题讨论】:

  • 你不需要两层角色和角色。而不是使用 XmlArray 使用 XmlElement。

标签: c# .net xml serialization


【解决方案1】:

需要使用XmlArrayItem属性

https://msdn.microsoft.com/en-us/library/vstudio/2baksw0z(v=vs.100).aspx

[Serializable]
public class Model
    {
        public string element = "elTest";
        [XmlArrayItem("role")]
        public List<String> roles;
    }
    class Program
    {
        static void Main(string[] args)
        {
            var me = new Model();
            me.roles = new List<string>()
        {
            "testString"
        };
            var ser = new XmlSerializer(me.GetType());
            using (var sw = new StreamWriter("0.xml"))
            {
                ser.Serialize(sw, me);
            }

            Console.ReadKey(true);
        }
}

另存为:

<?xml version="1.0" encoding="utf-8"?>
<Model xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <element>elTest</element>
  <roles>
    <role>testString</role>
  </roles>
</Model>

【讨论】:

    【解决方案2】:

    正是XmlArrayItem 解决了您的问题。

    【讨论】:

      猜你喜欢
      • 2011-09-28
      • 2010-11-17
      • 2018-10-30
      • 2012-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多