Adding Attributes to Elements - Exercise

Contact Us or call 1-877-932-8228
Adding Attributes to Elements - Exercise

Adding Attributes to Elements

Duration: 15 to 20 minutes.

In this exercise, you will modify the song schema, so that it can successfully validate Attributes/Exercises/TheGirlIsMine.xml.

  1. Open Attributes/Exercises/Song.xsd for editing.
  2. Change the schema so that the Title element can take the Type attribute, which is of type xs:string.
  3. Change the schema so that the Stanza element can take an Artist attribute, which is of type xs:string. The attribute should be required.
  4. Try to validate Attributes/Exercises/TheGirlIsMine.xml against the schema you just created. If the XML document is invalid, fix your schema.

Solution:

Attributes/Solutions/Song.xsd
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
	<xs:element name="Song">
		<xs:complexType>
			<xs:sequence>
				<xs:element name="Title">
					<xs:complexType>
						<xs:simpleContent>
							<xs:extension base="xs:string">
								<xs:attribute name="Type" type="xs:string"/>
							</xs:extension>
						</xs:simpleContent>
					</xs:complexType>
				</xs:element>
				<xs:element name="Year" type="xs:gYear"/>
				<xs:element name="Length" type="xs:string"/>
				<xs:element name="Artists">
					<xs:complexType>
						<xs:sequence>
							<xs:element name="Artist" type="xs:string" maxOccurs="unbounded"/>
						</xs:sequence>
					</xs:complexType>
				</xs:element>
				<xs:element name="Lyrics">
					<xs:complexType>
						<xs:sequence>
							<xs:element name="Stanza" maxOccurs="unbounded">
								<xs:complexType>
									<xs:sequence>
										<xs:element name="Line" type="xs:string" maxOccurs="unbounded"/>
									</xs:sequence>
									<xs:attribute name="Artist" use="required" type="xs:string"/>
								</xs:complexType>
							</xs:element>
						</xs:sequence>
					</xs:complexType>
				</xs:element>
			</xs:sequence>
		</xs:complexType>
	</xs:element>
</xs:schema>
Next