繁体   English   中英

属性未被XmlSerializer序列化

[英]attribute not being serialized by XmlSerializer

我想将类序列化为XML,为其分配XML属性。 片段:

    [XmlType(TypeName = "classmy")]
    public class MyClass2 : List<object>
    {
        [XmlAttribute(AttributeName = "myattr")]
        public string Name { get; set; }
    }

    public class MyConst
    {
        public MyConst()
        {
            MyClass2 myClass2 = new MyClass2 { 10, "abc" };

            myClass2.Name = "nomm";

            XmlSerializer serializer = new XmlSerializer(typeof(MyClass2));
            serializer.Serialize(Console.Out, myClass2);
        }
    }

但是生成的XML看起来像这样

<?xml version="1.0" encoding="IBM437"?>
<classmy xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <anyType xsi:type="xsd:int">10</anyType>
  <anyType xsi:type="xsd:string">abc</anyType>
</classmy>

一切都很好,唯一的例外是myClass2.Name没有被序列化。 我期待着一些东西

<classmy myattr="nomm" [...]>[...]</classmy>

...为什么不是序列化的,它怎么可能?

不要派生List<T> ,用成员List创建类

[XmlType(TypeName = "classmy")]
public class MyClass2
{
    [XmlAttribute(AttributeName = "Items")]
    List<object> Items { get; set; } //need to change type in `<>`

    [XmlAttribute(AttributeName = "myattr")]
    public string Name { get; set; }
}

XmlSerializer以特殊方式处理List <>:

如果满足某些要求,XmlSerializer可以处理实现IEnumerable或ICollection的类。 实现IEnumerable的类必须实现一个带有单个参数的公共Add方法。 Add方法的参数必须与从GetEnumerator方法返回的IEnumerator.Current属性返回的类型一致(多态)。 除了IEnumerable(例如CollectionBase)之外,实现ICollection的类必须具有公共Item索引属性(C#中的索引器),该属性采用整数,并且它必须具有integer类型的公共Count属性。 传递给Add方法的参数必须与Item属性返回的参数类型相同,或者是该类型的基础之一。 对于实现ICollection的类,将从索引的Item属性中检索要序列化的值,而不是通过调用GetEnumerator。 另请注意,除了返回另一个集合类(实现ICollection的集合类)的公共字段之外,公共字段和属性不会被序列化 MSDN - 滚动到XML序列化注意事项

这就是为什么它只将你的类序列化为一个对象列表,没有你的属性。 最好的解决方案是将List包含为类公共属性并将其标记为XmlElement。

替代解决方案:使用数组而不是列表和XmlElement

    [XmlType(TypeName = "classmy")]
    public class MyClass2
    {
        [XmlElement(ElementName = "Items")]
        public object[] Items { get; set; }
        [XmlAttribute(AttributeName = "myattr")]
        public string Name { get; set; }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM