【问题标题】:XmlSerialize a custom collection with an AttributeXmlSerialize 具有属性的自定义集合
【发布时间】:2010-09-27 12:13:06
【问题描述】:

我有一个简单的类,它继承自 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";
        }
    }
}

这会输出以下 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>

我想要的是

<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>

有什么想法吗?越简单越好。谢谢。

【问题讨论】:

    标签: c# .net xml-serialization


    【解决方案1】:

    集合通常不会成为额外属性的好地方。在序列化和数据绑定期间,如果项目看起来像一个集合(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
    }
    

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

    【讨论】:

      【解决方案2】:

      如果您确实按照 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>
      

      你可以有这个:

      <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>
      

      【讨论】:

      • @neilwhitaker1:我赞成这个答案,但如果你在答案中描述技术而不是让我们去阅读博客文章,那就更好了。您仍然可以参考该帖子。
      • 这篇博文以适当的详细程度很好地回答了这个问题,而且在博文中很容易找到答案。我认为在这种情况下链接到博客更可取。
      • @AndrewS 确实如此,直到十年后链接断开,您必须将其挖掘出来:docs.microsoft.com/en-us/archive/blogs/youssefm/…
      【解决方案3】:

      正如 Neil Whitaker 建议的那样,万一他的链接失效..

      创建一个内部集合来存储字符串并应用 XmlElement 属性来屏蔽集合名称。生成与从 Collection 继承的 MyCollection 相同的 xml 输出,但还会序列化父元素上的属性。

      [XmlRoot("MyCollection")]
      public class MyCollection 
      {
          [XmlAttribute()]
          public string MyAttribute { get; set; }
      
          [XmlElement("string")]
          public Collection<string> unserializedCollectionName { get; set; }
      
          public MyCollection()
          {
              this.MyAttribute = "SerializeThis";
              this.unserializedCollectionName = new Collection<string>();
              this.unserializedCollectionName.Add("Hello");
              this.unserializedCollectionName.Add("Goodbye");
          }
      }
      

      【讨论】:

        【解决方案4】:

        我一直在与 Romaroo 的相同问题作斗争(希望将属性添加到实现 ICollection 的类的 xml 序列化)。我还没有找到任何方法来公开集合类中的属性。我什至尝试使用 XmlAttribute 标记并使我的属性显示为根节点的属性,但也没有运气。但是,我能够在我的班级上使用 XmlRoot 标记将其从“ArrayOf ...”重命名。如果您有兴趣,这里有一些参考资料:

        【讨论】:

        • 看看我的解决方案,你可能会觉得很有趣。
        【解决方案5】:

        有时候你只想做你想做的事;框架该死。

        我在这里发布了答案Property of a List<T> Not Deserialized

        这就是 OP 想要做的。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-10-03
          • 2018-07-30
          • 2021-05-22
          • 2021-08-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-11-28
          相关资源
          最近更新 更多