XSD schema validation of XML

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="unqualified">
	<xs:element name="MyRootElement">
		<xs:annotation>
			<xs:documentation>Comment describing your root element</xs:documentation>
		</xs:annotation>
		<xs:complexType>
			<xs:sequence>
				<xs:element name="MySubElement"/>
				<xs:element name="MySubElementString" type="xs:string"/>
				
				<!-- by default elements are required -->
				<xs:element name="MySubElementOptional" minOccurs="0"/>

				<xs:element name="MySubElementRequiring3CharString">
					<xs:simpleType>
					
						<!-- restriction needs to have base type -->
						<xs:restriction base="xs:string">
							<xs:length value="3"/>
						</xs:restriction>
					</xs:simpleType>
				</xs:element>
				
				<xs:element name="MySubElementDisallowingText">
					<xs:complexType>
					</xs:complexType>
				</xs:element>
				
				<xs:element name="MySubElementWithOptionalAttrAndOptionalText" type="MySubElementWithOptionalAttrAndOptionalText" />

			</xs:sequence>
			
			<!-- attribute needs to be below sequence -->
			
			<xs:attribute name="myAttribute" type="xs:integer"/>
			
			<!-- by default attributes are optional -->
			<xs:attribute name="myRequiredAttribute" type="xs:integer" use="required"/>
			
		</xs:complexType>
	</xs:element>
	
	<xs:complexType name="MySubElementWithOptionalAttrAndOptionalText">
		<xs:simpleContent>
			<xs:extension base="xs:string">
				<xs:attribute name="myIntegerAttribute" />
			</xs:extension>
		</xs:simpleContent>
	</xs:complexType>
</xs:schema>
<?xml version="1.0" encoding="UTF-8"?>
<MyRootElement xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" myAttribute="0" myRequiredAttribute="0" xsi:noNamespaceSchemaLocation="my-schema.xsd">
	<MySubElement>text</MySubElement> <!-- can be replaced with: <MySubElement /> -->
	<MySubElementString>String</MySubElementString> <!-- can be replaced with: <MySubElementString /> -->
	<MySubElementOptional>text</MySubElementOptional> <!-- can be completely removed -->
	<MySubElementRequiring3CharString>aaa</MySubElementRequiring3CharString>
	<MySubElementDisallowingText/>
	<MySubElementWithOptionalAttrAndOptionalText myIntegerAttribute="text">String</MySubElementWithOptionalAttrAndOptionalText>
	<!-- can be replaced with: 	<MySubElementWithOptionalAttrAndOptionalText /> -->
</MyRootElement>

my-schema.xsd

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s