I need to define an element with multiple patterns, like gDay, gMonth, gYear, dateTime, etc. How can I define a restriction in XSD to do that?
Someting like this:
<dates>
<out>2012</out>
</dates>
<xs:complexType name="infodates">
<xs:sequence>
<xs:element name="out" type="xs:dateTime"&"xs:gMonth"/>
</xs:sequence>
</xs:complexType>
Thanks
Short answer: xml schema can’t concatenate simple datatypes.
It might not be what you want anyway:
xs:gMonthrequires a double-hyphen prefix (e.g. “–05”), andxs:gDayneeds a triple-hyphen (e.g. “—31”). Not what I expected!Here’s examples for each simple datatype. There’s some combined types built-in too:
gYearMonth,gMonthDayetc.Along these lines,
xs:dateTimehas a long definition:'-'? yyyy '-' mm '-' dd 'T' hh ':' mm ':' ss ('.' s+)? (zzzzzz)?Only three parts can be left out, so it needsyyyy-mm-ddThh:mm:ss– your example in<out>2012</out>isn’t valid with respect to this.Long answer: However, xml schema can combine simple datatypes by
union(like choice) andlist(space-separated list of the same type). So, you can do something like:(gDay|gMonth|gYear|dateTime)*(not valid xsd syntax, just illustrative). This isn’t ordered and allows duplicates, so e.g. “—31 –05 –05” is valid. Here it is in xsd syntax:Conclusion: You can’t reuse the built-in datatypes in the way you (and I) would like, and they don’t seem very nice anyway. You’re probably better off explicitly defining it yourself, as in InfantProgrammer’Aravind’s answer. (Or, you could use separate attributes for each component instead – which would make it easier for whoever is parsing it, too).
For fun, I tried shortening InfantProgrammer’Aravind’s answer (though it’s arguable whether this makes it clearer…). It retains the check of 12-hour with am/pm vs. 24-hour without am/pm (but doesn’t accept empty aka null value).
Here’s a brief guide to regex in XSD; here’s a long one.
BTW: Turns out you can denote “[1-9]” as “[\d-[0]]”, which is a “Character Class Subtraction“, not a range.