c# - 派生类

时间:2018-01-30 09:37:25

标签: c# xml serialization xml-serialization

我知道在通过XmlArrayItem属性使用XmlSerializer时,我可以为list-elements指定xml-element-names。但这仅适用于列表,即字段(或属性)。有没有办法为任何列表设置它?

示例:

[XmlInclude(typeof(Foo1)), 
XmlInclude(typeof(Foo2))]
public abstract class Bar {
    public string s;
}

public class Foo1 : Bar { }
public class Foo2 : Bar { }

public class Test {
    [XmlArray("Bars"),
    XmlArrayItem(typeof(Foo1), ElementName = "derived1"),
    XmlArrayItem(typeof(Foo2), ElementName = "derived2"),
    XmlArrayItem(typeof(FluxObjectData), ElementName = "base")]
    public List<Bar> list;

    public Test() { }
    public Test(List<Bar> list) {
        this.list = list;
    }
}

使用方法A:

XmlWriter write = GetWriter();
Test test = GetTest();
XmlSerializer serializer = new XmlSerializer(test.GetType());
serializer.Serialize(writer, test);

xml A看起来像:

<Bars>
    <derived1>
      <s>s1_1</s>
    </derived1>
    <derived1>
      <s>s1_2</s>
    </derived1>
    <derived1>
      <s>s1_3</s>
    </derived1>
    <derived2>
      <s>s2_1</s>
    </derived2>
  </Bars>

然而,当使用方法B时

XmlWriter otherWriter = GetOtherWriter();
List<Bar> bars = test.list;
XmlAttributeOverrides overrides = new XmlAttributeOverrides();
overrides.Add(typeof(Foo1), new XmlAttributes {
    XmlType = new XmlTypeAttribute("derived1")
});
overrides.Add(typeof(Foo2), new XmlAttributes {
    XmlType = new XmlTypeAttribute("derived2")
});
overrides.Add(typeof(Bar), new XmlAttributes {
    XmlType = new XmlTypeAttribute("base")
});
serializer = new XmlSerializer(bars.GetType(), overrides, Type.EmptyTypes, new XmlRootAttribute("Bars"), "");
serializer.Serialize(otherWriter, bars);

xml B看起来像:

<Bars>
  <base xsi:type="derived1">
    <s>s1_1</s>
  </base>
  <base xsi:type="derived1">
    <s>s1_2</s>
  </base>
  <base xsi:type="derived1">
    <s>s1_3</s>
  </base>
  <base xsi:type="derived2">
    <s>s2_1</s>
  </base>
</Bars>

如何使用方法B获取xml A?

提前致谢

0 个答案:

没有答案