Uniqueness

Contact Us or call 1-877-932-8228
Uniqueness

Uniqueness

XML Schema provides a mechanism for requiring that each element be unique among like elements.

This is best illustrated with an example:

Code Sample:

SchemaKeys/Demos/Unique.xsd
---- C O D E   O M I T T E D ----
				<xs:element name="Artists">
					<xs:complexType>
						<xs:sequence>
							<xs:element name="Artist" maxOccurs="unbounded">
								<xs:complexType>
									<xs:simpleContent>
										<xs:extension base="xs:string">
											<xs:attribute name="aID" type="xs:string" use="required"/>
										</xs:extension>
									</xs:simpleContent>
								</xs:complexType>
							</xs:element>
						</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" type="xs:string"/>
								</xs:complexType>
							</xs:element>
						</xs:sequence>
					</xs:complexType>
				</xs:element>
			</xs:sequence>
		</xs:complexType>
		<xs:unique name="ArtistKey">
			<xs:selector xpath="Artists/Artist"/>
			<xs:field xpath="@aID"/>
		</xs:unique>
	</xs:element>
</xs:schema>

The Artist element has an aID attribute, which we would like to be able to use to uniquely identify the artist. The XML Schema xs:unique element is used to enforce this. It takes two children:

  • xs:selector - takes an xpath attribute which holds an XPath 1.0 expression referencing the elements affected by this constraint.
  • xs:field - takes an xpath attribute which holds an XPath 1.0 expression specifying the part of the selected elements that must be unique.

In the example above, the selector XPath identifies all Artist elements that are children of an Artists element. The field XPath identifies the aID attribute as the part of the Artist element that must be unique.

In the XML instance below, each Artist must have a unique aID attribute. Try making them the same and validating.

Code Sample:

SchemaKeys/Demos/Unique.xml
<?xml version="1.0"?>
<Song xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="Unique.xsd">
	<Title Type="duet">The Girl Is Mine</Title>
	<Year>1983</Year>
	<Length>Medium</Length>
	<Artists>
		<Artist aID="MJ">Michael Jackson</Artist>
		<Artist aID="PM">Paul McCartney</Artist>
	</Artists>
---- C O D E   O M I T T E D ----

</Song>
Next