使用XmlInclude或SoapInclude属性指定静态未知的类型

时间:2012-08-09 15:00:38

标签: c# .net xml xmlserializer

使用.NET的XmlSerializer时,我遇到了一个非常奇怪的问题。

采用以下示例类:

public class Order 
{
    public PaymentCollection Payments { get; set; }

    //everything else is serializable (including other collections of non-abstract types)
}

public class PaymentCollection : Collection<Payment>
{
}

public abstract class Payment 
{
    //abstract methods
}

public class BankPayment : Payment
{
    //method implementations
}

AFAIK,解决InvalidOperationException有三种不同的方法,这些方法是由序列化程序不知道Payment的派生类型引起的。

1。将XmlInclude添加到Payment类定义:

这是不可能的,因为所有类都包含在我无法控制的外部引用中。

2。在创建XmlSerializer实例

期间传递派生类型的类型

不起作用。

第3。为目标属性定义XmlAttributeOverrides以覆盖属性的默认序列化(如this SO post中所述)

也不起作用(XmlAttributeOverrides初始化跟随)。

Type bankPayment = typeof(BankPayment);

XmlAttributes attributes = new XmlAttributes();
attributes.XmlElements.Add(new XmlElementAttribute(bankPayment.Name, bankPayment));

XmlAttributeOverrides overrides = new XmlAttributeOverrides();
overrides.Add(typeof(Order), "Payments", attributes);

然后将使用适当的XmlSerializer构造函数。

注意:不起作用我的意思是InvalidOperationException BankPayment不是预期的...... )。

任何人都可以对这个问题有所了解吗?如何进一步调试问题?

5 个答案:

答案 0 :(得分:78)

这对我有用:

[XmlInclude(typeof(BankPayment))]
[Serializable]
public abstract class Payment { }    

[Serializable]
public class BankPayment : Payment {} 

[Serializable]
public class Payments : List<Payment>{}

XmlSerializer serializer = new XmlSerializer(typeof(Payments), new Type[]{typeof(Payment)});

答案 1 :(得分:35)

刚刚解决了这个问题。经过一段时间的挖掘后,我发现this SO post涵盖了完全相同的情况。它让我走上正轨。

基本上,XmlSerializer需要知道默认名称空间,如果派生类作为额外类型包含在内。这种情况发生的确切原因尚不清楚,但是,序列化现在仍然有效。

答案 2 :(得分:2)

我同意bizl

[XmlInclude(typeof(ParentOfTheItem))]
[Serializable]
public abstract class WarningsType{ }

如果您需要将此包含的类应用于对象项目,也可以这样做

[System.Xml.Serialization.XmlElementAttribute("Warnings", typeof(WarningsType))]
public object[] Items
{
    get
    {
        return this.itemsField;
    }
    set
    {
        this.itemsField = value;
    }
}

答案 3 :(得分:0)

基于this,我可以通过更改所使用的XmlSerializer的构造函数来解决此问题,而无需更改类。

不要使用这样的东西(在其他答案中建议):

[XmlInclude(typeof(Derived))]
public class Base {}

public class Derived : Base {}

public void Serialize()
{
    TextWriter writer = new StreamWriter(SchedulePath);
    XmlSerializer xmlSerializer = new XmlSerializer(typeof(List<Derived>));
    xmlSerializer.Serialize(writer, data);
    writer.Close();
}

我这样做了:

public class Base {}

public class Derived : Base {}

public void Serialize()
{
    TextWriter writer = new StreamWriter(SchedulePath);
    XmlSerializer xmlSerializer = new XmlSerializer(typeof(List<Derived>), new[] { typeof(Derived) });
    xmlSerializer.Serialize(writer, data);
    writer.Close();
}

答案 4 :(得分:0)

只需在Base中执行此操作,这样就可以将任何子级序列化,减少代码清理程序的代码。

public abstract class XmlBaseClass  
{
  public virtual string Serialize()
  {
    this.SerializeValidation();

    XmlSerializerNamespaces XmlNamespaces = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty });
    XmlWriterSettings XmlSettings = new XmlWriterSettings
    {
      Indent = true,
      OmitXmlDeclaration = true
    };

    StringWriter StringWriter = new StringWriter();

    XmlSerializer Serializer = new XmlSerializer(this.GetType());
    XmlWriter XmlWriter = XmlWriter.Create(StringWriter, XmlSettings);
    Serializer.Serialize(XmlWriter, this, XmlNamespaces);
    StringWriter.Flush();
    StringWriter.Close();

    return StringWriter.ToString();

  }

  protected virtual void SerializeValidation() {}
}

[XmlRoot(ElementName = "MyRoot", Namespace = "MyNamespace")]
public class XmlChildClass : XmlBaseClass
{
  protected override void SerializeValidation()
  {
    //Add custom validation logic here or anything else you need to do
  }
}

这样,无论何种情况,您都可以在子类上调用序列化,并且仍然可以执行对象序列化之前需要做的事情。