108

在使用 .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.添加XmlIncludePayment类定义:

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

XmlSerializer2. 在创建实例时传递派生类型的类型

不工作。

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不是预期的... ) 被抛出。

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

4

5 回答 5

101

这对我有用:

[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)});
于 2012-11-23T12:23:29.220 回答
40

刚刚解决了问题。在挖掘了一段时间后,我发现这篇 SO 帖子涵盖了完全相同的情况。它让我走上了正轨。

基本上,如果派生类作为额外类型包含在内,则XmlSerializer需要知道默认命名空间。必须发生这种情况的确切原因仍然未知,但序列化现在仍在工作。

于 2012-08-09T17:09:41.123 回答
5

基于,我能够通过更改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();
}
于 2019-06-04T14:43:43.243 回答
3

只需在 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
  }
}

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

于 2019-10-09T23:08:56.493 回答
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;
    }
}
于 2020-01-17T20:48:10.420 回答