如何序列化为XmlChoice

How to serialize into XmlChoice

我使用 existing xsd schema 中的 xsd.exe 生成了 C# 类。它生成以下 属性:

public class TrackRequestSearchCriteria {

[System.Xml.Serialization.XmlElementAttribute("ConsignmentNumber", typeof(string))]
[System.Xml.Serialization.XmlElementAttribute("PieceReference", typeof(string))]
[System.Xml.Serialization.XmlChoiceIdentifierAttribute("ItemsElementName")]
public object[] Items {
    get {
        return this.itemsField;
    }
    set {
        this.itemsField = value;
    }
}

预期的 xml 是:

<SearchCriteria>
    <ConsignmentNumber>#1</ConsignmentNumber>
</SearchCriteria>

如何初始化 Items 属性,使其序列化为 <ConsignmentNumber>#1</ConsignmentNumber>

new SomeRootElement {
   Items = new Object[] {
      // how to add ConsignmentNumber here
   }
}

@AlexanderPetrov

我用xsd.exe根据给出的方案生成了一组类。

下面的代码给出了想要的 xml.

var trackRequest = new TrackRequest
{
    SearchCriteria = new TrackRequestSearchCriteria
    {
        Items = new object[] { "#1" }, // new string[]
        ItemsElementName = new ItemsChoiceType[] { ItemsChoiceType.ConsignmentNumber }
    }
};
 
var xs = new XmlSerializer(typeof(TrackRequest));
xs.Serialize(Console.Out, trackRequest);