开发者

What is the correct way to allow different values for an XML element in a schema?

I have the following XML schema where I'm trying to allow for 2 different values for an element:

<?xml version="1.0" encoding="utf-8" ?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
  <xs:simpleType name="DATE_MM_DD_YYYY">
    <xs:restriction base="xs:string">
      <xs:pattern value="[0-1][0-9]/[0-3][0-9]/[0-9]{4}"/>
    </xs:restriction>
  </xs:simpleType>
  <xs:simpleType name="DATE_MM_DD_YY">
    <xs:restriction base="xs:string">
      <xs:pattern value="[0-1][0-9]/[0-3][0-9]/[0-9]{2}"/>
    </xs:restriction>
  </xs:simpleType>
  <xs:element name="Transaction">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="Date1" type="DATE_MM_DD_YYYY" />
        <xs:choice>
          <xs:elem开发者_如何学Cent name="Date2" type="DATE_MM_DD_YYYY" />
          <!--Error-->
          <xs:element name="Date2" type="DATE_MM_DD_YY" />
        </xs:choice>
        <xs:element name="Field1" />
        <xs:element name="Field2" />
        <xs:element name="Field3" />
        <!--...-->
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

I want the Element called "Date2" to be specified in 2 different formats.

I can't seem to get "xs:choice" to work, and I'm thinking that I might need to define a new pattern that allows either or the 2 formats.

What is the correct way to do this?


You can use alternation and grouping in xml schema patterns. Eg, ([0-9]{2}|[0-9]{4}).

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
  <xs:simpleType name="DATE_MM_DD_YYYY">
    <xs:restriction base="xs:string">
      <xs:pattern value="[0-1][0-9]/[0-3][0-9]/[0-9]{4}"/>
    </xs:restriction>
  </xs:simpleType>
  <xs:simpleType name="FLEXDATE">
    <xs:restriction base="xs:string">
      <xs:pattern value="[0-1][0-9]/[0-3][0-9]/([0-9]{2}|[0-9]{4})"/>
    </xs:restriction>
  </xs:simpleType>
  <xs:element name="Transaction">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="Date1" type="DATE_MM_DD_YYYY" />
        <xs:element name="Date2" type="FLEXDATE" />
        <xs:element name="Field1" type='xs:string' />
        <xs:element name="Field2" type='xs:string' />
        <xs:element name="Field3" type='xs:string' />
        <!--...-->
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

ps: I think your patterns could be more strict. As they are, a date of 00/00/0000 passes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜