0

我有这部分和.xsd:

  <xs:element name="TimePeriod" nillable="false">
    <xs:complexType>
      <xs:choice>
        <xs:element name="StartTime" type="xs:dateTime" nillable="false"/>
        <xs:element name="StopTime" type="xs:dateTime" nillable="false"/>
      </xs:choice>
    </xs:complexType>
  </xs:element>

使用我从 xsd2code 获得的这段代码:

public partial class ActivityTYPETimePeriod
{
    private System.DateTime itemField;
    private ItemChoiceType itemElementNameField;

    public System.DateTime Item
    {
        get
        {
            return this.itemField;
        }
        set
        {
            this.itemField = value;
        }
    }

    [System.Xml.Serialization.XmlIgnoreAttribute()]
    public ItemChoiceType ItemElementName
    {
        get
        {
            return this.itemElementNameField;
        }
        set
        {
            this.itemElementNameField = value;
        }
    }
}

public enum ItemChoiceType
{
    /// <remarks/>
    StartTime,
    /// <remarks/>
    StopTime,
}

这给了我这个输出:

<TimePeriod>
    <Item>2016-11-07T09:50:41.27</Item>
</TimePeriod>

但如果 StartTime 是枚举选择,我希望是这样的:

<TimePeriod>
    <StartTime>2016-11-07T09:50:41.27</StartTime>
</TimePeriod>

但是当我使用这个装饰时(也来自 xsd2code):

[System.Xml.Serialization.XmlChoiceIdentifierAttribute("ItemElementName")]
public System.DateTime Item

我抛出一个异常说:

{“缺少选择‘Item’的序列化所需的‘TimeElementName’成员。”}

我无法解释为什么它会引发此错误,因为我似乎记得在我编辑班级的其他部分之前它正在工作,并且当我调试代码时,它也收到TimePeriod了正确的值并且直到异常才被抛出我打了这一行: var serializer = new XmlSerializer(this.GetType());

有没有另一种方法来获得我想要的输出或解决这个异常。

4

1 回答 1

0

我发现 xsd2code 由于某种原因没有生成的缺少的部分是它工作所需的这两行代码:

[System.Xml.Serialization.XmlElementAttribute("EndTime", typeof(System.DateTime))]
[System.Xml.Serialization.XmlElementAttribute("StartTime", typeof(System.DateTime))]

所以得到的装饰Item是这样的:

[System.Xml.Serialization.XmlElementAttribute("Sluttidpunkt", typeof(System.DateTime))]
[System.Xml.Serialization.XmlElementAttribute("Starttidpunkt", typeof(System.DateTime))]
[System.Xml.Serialization.XmlChoiceIdentifierAttribute("ItemElementName")]
public System.DateTime Item
于 2016-11-09T12:29:07.177 回答