使用XmlChoiceIdentifierAttribute序列化派生类成员

时间:2017-08-02 23:36:10

标签: c# xml

我有WSDL服务类,我想在其中添加额外的属性。当我试图反序列化我的派生类时,它给出错误“你需要将XmlChoiceIdentifierAttribute添加到'ObjCreatePaperClipTransaction'成员。”

这是我在服务类之上编写的代码。 (executeCreatePaperClipTransaction& CreatePaperClipTransactionType是来自代理对象的类

namespace MyProject.DTO
{
    [XmlType("executeCreatePaperClipTransaction")]
    public partial class CustomExecuteCreatePaperClipTransaction : executeCreatePaperClipTransaction
    {
        [XmlElement(Form = System.Xml.Schema.XmlSchemaForm.Unqualified, Order = 0)]
        [XmlElement("CreatePaperClipTransaction")]
        public CustomCreatePaperClipTransactionType ObjCreatePaperClipTransaction { get; set; }        
    }    

    public partial class CustomCreatePaperClipTransactionType : CreatePaperClipTransactionType
    {
        [XmlElement(Form = System.Xml.Schema.XmlSchemaForm.Unqualified, Order = 0)]
        public executeCreateLoanIncrease ObjLoanIncreaseRequest { get; set; }

        [XmlElement(Form = System.Xml.Schema.XmlSchemaForm.Unqualified, Order = 1)]
        public executeCreateFreeFormEventFeePayment ObjFreeFormEventFeePaymentRequest { get; set; }
        }
    }

当我删除[XmlElement("CreatePaperClipTransaction")]行时,它的工作正常。但在seralized xml中我希望标记名称为CreatePaperClipTransaction而不是ObjCreatePaperClipTransaction

我仔细阅读了这个答案,但我不确定如何在我的案例https://stackoverflow.com/a/20379038/1169180

中实施

1 个答案:

答案 0 :(得分:0)

您应该添加一个包含所有必要信息的单个属性,而不是向ObjCreatePaperClipTransaction属性添加两个单独的[XmlElement]属性:

[XmlType("executeCreatePaperClipTransaction")]
public partial class CustomExecuteCreatePaperClipTransaction : executeCreatePaperClipTransaction
{
    [XmlElement(ElementName = "CreatePaperClipTransaction", Form = System.Xml.Schema.XmlSchemaForm.Unqualified, Order = 0)]
    public CustomCreatePaperClipTransactionType ObjCreatePaperClipTransaction { get; set; }        
}    

工作.Net fiddle

当您向属性添加多个[XmlElement]属性时,您通知XmlSerializer 应将多个不同的XML元素名称绑定到同一属性,例如因为属性值是多态的:

public class BaseClass
{
}

public class DerivedClass : BaseClass
{
}

public class RootObject
{
    [XmlElement(ElementName = "BaseClassProperty", Type = typeof(BaseClass))]
    [XmlElement(ElementName = "DerivedClassProperty", Type = typeof(DerivedClass))]
    public BaseClass Property { get; set; }
}

在上面的示例中,如果为Property分配了DerivedClass值,则会生成以下XML:

<RootObject>
  <DerivedClassProperty />
</RootObject>

这似乎不适用于此。您只想将属性绑定到XML元素名称<CreatePaperClipTransaction>