我有一个表示信用卡详细信息的类。为了表示从和过期几个月甚至几年有效,我使用int
类型的四个属性:使用XML序列化格式化元素/属性值
public int ValidFromMonth { get; set; }
public int ValidFromYear { get; set; }
public int ExpiresEndMonth { get; set; }
public int ExpiresEndYear { get; set; }
我XML由第三方序列化这个类消费。第三方需要我的月份和年份值与前导零作为前缀,如果该值小于10
<validFromMonth>02</validFromMonth>
<validFromYear>09</validFromYear>
<expiresEndMonth>10</expiresEndMonth>
<expiresEndYear>14</expiresEndYear>
是否.NET支持的任何属性(或者是我能够创建一个自定义属性)将执行此规则,可能使用格式字符串(例如{0:00}
)?
注:我知道我可以添加自己的string
性能在内部做了格式化,并添加[XmlIgnore]
属性我int
属性,但这种感觉就像一个二流的解决方案。
编辑: 经过一些考虑,我想知道这实际上是不可行的。序列化不成问题,但为了反序列化工作,您需要取消格式化序列化的字符串。在上面这个简单的例子中,这很容易,但我不确定是否可以在更一般的情况下工作。
编辑2: 定义两位数要求的XML架构如下。
简单类型定义:
使用这些类型的<xs:simpleType name="CreditCardMonthType">
<xs:annotation>
<xs:documentation>Two digit month</xs:documentation>
</xs:annotation>
<xs:restriction base="xs:string">
<xs:minLength value="2" />
<xs:maxLength value="2" />
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="CreditCardYearType">
<xs:annotation>
<xs:documentation>Two digit year</xs:documentation>
</xs:annotation>
<xs:restriction base="xs:string">
<xs:minLength value="2" />
<xs:maxLength value="2" />
</xs:restriction>
</xs:simpleType>
信用卡的定义:
<xs:attribute name="ExpiryMonth" type="CreditCardMonthType" use="required">
<xs:annotation>
<xs:documentation>Credit/debt card's expiry month.</xs:documentation>
</xs:annotation>
</xs:attribute>
<xs:attribute name="ExpiryYear" type="CreditCardYearType" use="required">
<xs:annotation>
<xs:documentation>Credit/debt card's expiry year.</xs:documentation>
</xs:annotation>
</xs:attribute>
<xs:attribute name="StartMonth" type="CreditCardMonthType" use="optional">
<xs:annotation>
<xs:documentation>Switch card's start month.</xs:documentation>
</xs:annotation>
</xs:attribute>
<xs:attribute name="StartYear" type="CreditCardYearType" use="optional">
<xs:annotation>
<xs:documentation>Switch card's start year.</xs:documentation>
</xs:annotation>
</xs:attribute>
这是极好的 - 但我想我还是会需要多年来一直使用LeadingZero类的方法。 – 2009-04-27 10:24:32
也许吧。这就是我放弃它的原因。我认为他们是不同的足以保证他们作为单独的答案(取决于你的需要)。我真的会看到让他们将年份字段扩大到4位数字。我的意思是,来吧,他们已经使用了冗长的格式(XML),他们认为他们通过仅使用两位数字来节省多少时间?但我明白,如果你坚持使用他们的架构。无论哪种方式,这两件事应该有助于完成你所需要的。 – 2009-04-27 12:52:37