Restricting Element Content - Exercise

Contact Us or call 1-877-932-8228
Restricting Element Content - Exercise

Restricting Element Content

Duration: 15 to 20 minutes.

In this exercise, you will further restrict the Song schema, so that the Title and Artist elements will have a specified pattern and the Year will be between 1950 and 1970.

  1. Open SimpleTypes/Exercises/Song.xsd and save it as Song2.xsd in the same directory.
  2. Define a simple type called ProperName that follows this pattern. Note that the only space in the pattern is the one before the question mark.
    ([A-Z0-9][A-Za-z0-9\-']* ?)+
  3. Change the Title and Artist elements to be of the ProperName type.
  4. Define another simple type called Year, which is derived from gYear and only accepts years between 1950 and 1970, inclusive.
  5. Change the Year element to be of the Year type.
  6. Try to validate SimpleTypes/Exercises/CantBuyMeLove.xml against the schema you just created. If the XML document is invalid, fix your schema.

Code Sample:

SimpleTypes/Exercises/Song.xsd
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
	<xs:element name="Song">
		<xs:complexType>
			<xs:sequence>
				<!--
					Add three simple-type elements:
					1. Title
					2. Year
					3. Artist
				-->
			</xs:sequence>
		</xs:complexType>
	</xs:element>
</xs:schema>

Solution:

SimpleTypes/Solutions/Song2.xsd
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
	<xs:simpleType name="ProperName">
		<xs:restriction base="xs:string">
			<xs:pattern value="([A-Z0-9][A-Za-z0-9\-']* ?)+"/>
			<xs:whiteSpace value="collapse"/>
		</xs:restriction>
	</xs:simpleType>
	<xs:simpleType name="Year">
		<xs:restriction base="xs:gYear">
			<xs:minInclusive value="1950"/>
			<xs:maxInclusive value="1970"/>
		</xs:restriction>
	</xs:simpleType>
	<xs:element name="Song">
		<xs:complexType>
			<xs:sequence>
				<xs:element name="Title" type="ProperName"/>
				<xs:element name="Year" type="Year"/>
				<xs:element name="Artist" type="ProperName"/>
			</xs:sequence>
		</xs:complexType>
	</xs:element>
</xs:schema>
Next