I was working through XML schema today and stumble upon an unusual but relevant problem. I wanted schema to validate an element having a mandatory attribute and optional integer text node.
For example :
Code snippet in green should validate, where as code snippet in red should result in validation failure.
[VALID]
<root GUID="guid1">
<element GUID="guid2"/>
<element GUID="guid3">23</element>
</root>
[/VALID]
[INVALID]
<root GUID="guid1">
<element GUID="guid2"/>
<element GUID="guid3">str</element>
</root>
[/INVALID]
[INVALID]
<root GUID="guid1">
<element GUID="guid2"/>
<element>12</element>
</root>
[/INVALID]
To achieve this, one needs to use simple types and extensions. XML code block below solves above mentioned problem.
[CODE]
<!-==== Schema Elements ====-->
<xs:element name="root">
<xs:complexType>
<xs:sequence>
<xs:element ref="element" minOccurs="1" maxOccurs="unbounded" />
</xs:sequence>
<xs:attribute ref="GUID" use="required" />
</xs:complexType>
</xs:element>
<xs:element name="element">
<xs:complexType>
<xs:simpleContent>
<xs:extension base="integerPattern">
<xs:attribute ref="GUID" use="required" />
</xs:extension>
</xs:simpleContent>
</xs:complexType>
</xs:element>
<!-===== Attributes ============-->
<xs:attribute name="GUID" type="xs:string" />
<!-====== Simple Types =========-->
<xs:simpleType name="integerPattern">
<xs:union>
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:minLength value="0" />
<xs:pattern value="([0-9])*" />
</xs:restriction>
</xs:simpleType>
</xs:union>
</xs:simpleType>
[/CODE]
Cheers
Wednesday, August 6, 2008
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment