XmlSerialize具有Attribute的自定义集合

roo*_*roo 19 .net c# xml-serialization

我有一个继承自Collection的简单类,并添加了几个属性.我需要将此类序列化为XML,但XMLSerializer忽略了我的其他属性.

我假设这是因为XMLSerializer提供ICollection和IEnumerable对象的特殊处理.最好的方法是什么?

这是一些示例代码:

using System.Collections.ObjectModel;
using System.IO;
using System.Xml.Serialization;

namespace SerialiseCollection
{
    class Program
    {
        static void Main(string[] args)
        {
            var c = new MyCollection();
            c.Add("Hello");
            c.Add("Goodbye");

            var serializer = new XmlSerializer(typeof(MyCollection));
            using (var writer = new StreamWriter("test.xml"))
                serializer.Serialize(writer, c);
        }
    }

    [XmlRoot("MyCollection")]
    public class MyCollection : Collection<string>
    {
        [XmlAttribute()]
        public string MyAttribute { get; set; }

        public MyCollection()
        {
            this.MyAttribute = "SerializeThis";
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这将输出以下XML(注意MyCollection元素中缺少MyAttribute):

<?xml version="1.0" encoding="utf-8"?>
<MyCollection xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <string>Hello</string>
    <string>Goodbye</string>
</MyCollection>
Run Code Online (Sandbox Code Playgroud)

想要的

<MyCollection MyAttribute="SerializeThis" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <string>Hello</string>
    <string>Goodbye</string>
</MyCollection>
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?越简单越好.谢谢.

Mar*_*ell 14

收藏品通常不会为额外的物业提供好地方.无论是在序列化和数据绑定,如果该项目看起来像一个集合,他们将被忽略(IList,IEnumerable,等-根据情况).

如果是我,我会封装集合 - 即

[Serializable]
public class MyCollectionWrapper {
    [XmlAttribute]
    public string SomeProp {get;set;} // custom props etc
    [XmlAttribute]
    public int SomeOtherProp {get;set;} // custom props etc
    public Collection<string> Items {get;set;} // the items
}
Run Code Online (Sandbox Code Playgroud)

另一种选择是实现IXmlSerializable(相当多的工作),但仍然不适用于数据绑定等.基本上,这不是预期的用法.


Nei*_*eil 13

如果你进行封装,正如Marc Gravell建议的那样,这篇文章的开头解释了如何让你的XML看起来与你描述的完全一样.

http://blogs.msdn.com/youssefm/archive/2009/06/12/customizing-the-xml-for-collections-with-xmlserializer-and-datacontractserializer.aspx

也就是说,而不是这个:

<MyCollection MyAttribute="SerializeThis" 
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Items>
    <string>Hello</string>
    <string>Goodbye</string>
  <Items>
</MyCollection>
Run Code Online (Sandbox Code Playgroud)

你可以这样:

<MyCollection MyAttribute="SerializeThis" 
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  xmlns:xsd="http://www.w3.org/2001/XMLSchema">      
  <string>Hello</string>
  <string>Goodbye</string>
</MyCollection>
Run Code Online (Sandbox Code Playgroud)