XML Schema Definition (XSD) Guide

Explore our comprehensive XML Schema Definition (XSD) Guide for students. Learn to define, validate, and structure XML documents with practical examples and SEO insights. Start mastering XSD today!

Podcast

XML Schéma: Stavební plán pro vaše data0:00 / 15:07
0:001:00 remaining

Welcome to this essential XML Schema Definition (XSD) Guide, designed for students to master XML document validation and structure. XSD is a powerful language used to describe the structure and data types of XML documents, offering a robust alternative to DTDs. This guide will walk you through its core concepts, practical applications, and advanced features, ensuring you understand how to define, reference, and validate your XML files effectively.

What is XML Schema Definition (XSD)?

XML Schema Definition (XSD) is an XML-based language for describing the structure and data constraints of XML documents. Unlike its predecessor, Document Type Definition (DTD), XSD itself is written in XML, utilizing namespaces and a more extensive set of features. XSD files typically use the *.xsd extension.

Key characteristics of XSD include:

  • It serves as an alternative to DTD, offering greater power and flexibility.
  • It provides a detailed description of an XML document's structure and data types.
  • It uses XML syntax, removing the need for special parsing tools for the schema itself.
  • It specifies how an XML parser should interact with and validate an XML document.

Why Use XML Schema Definition?

XSD is crucial for several reasons in data exchange and document processing:

  • Specify Data Format: It defines the precise format that data within an XML document must adhere to.
  • Guide Document Creation: It provides a blueprint for how to construct a specific XML document correctly.
  • Validate XML Structure: It allows you to check whether a created XML document conforms to the desired structure and rules.
  • Ensure Data Validity: It verifies that provided XML data is valid before further processing, preventing errors down the line.

What XSD Allows You To Do

XSD offers extensive capabilities for defining XML document properties:

  • Define Elements and Attributes: You can specify elements, their attributes, and other XML parts.
  • Describe Hierarchical Structure: XSD accurately models the parent-child relationships, lists, and the order of elements (using sequence, all, choice).
  • Control Element Occurrences: It precisely determines the minimum and maximum number of times an element can appear (minOccurs, maxOccurs).
  • Define Data Types: Similar to programming languages, XSD supports various built-in data types (e.g., string, integer, date).
  • Implement Restrictions and Custom Types: You can apply restrictions to existing data types or create entirely new custom data types.
  • Specify Default or Fixed Values: Elements and attributes can be assigned default or unchangeable fixed values.
  • Connect Content from Other Documents: XSD can link and incorporate content definitions from external schemas.

Advantages of XML Schema Definition (XSD)

XSD provides significant advantages over DTDs:

  • Extensibility: It is designed to be extensible, allowing for future growth and adaptation.
  • Richer Features: XSD offers a broader range of features compared to DTDs, especially in data type definition.
  • XML Syntax: Being written in XML makes it easier to process with standard XML tools.
  • Namespace Support: It supports and leverages XML namespaces for managing element and attribute names.
  • Robust Data Validation: XSD allows for strong data type validation, checking not just structure but also specific data properties like character count, numeric ranges, and date formats.

Comparing DTD vs. XSD: A Deeper Look

When considering DTD (Document Type Definition) versus XSD, it's essential to understand their strengths and weaknesses for XML document validation. Both serve to define XML document structure, but XSD is generally preferred for its advanced features.

FeatureDTD (Document Type Definition)XML Schema Definition (XSD)
ComplexitySimpler, clearerMore complex, more powerful
SyntaxNon-XML syntaxXML syntax (an XML document itself)
Data TypesBasic, limitedExtensive, supports custom types
NamespacesNot supportedFully supported
ReadabilityShorter for small, basic documentsCan be shorter for complex documents
FeaturesBasic validation, limited featuresMuch more features, rich validation
ExtensibilityLimitedHighly extensible

For basic validation and smaller documents, DTDs can be quicker to write. However, for complex, extensive documents requiring strict data type checking, XSD's capabilities make it the superior choice.

XSD Validation Process and Referencing

To ensure your XML document adheres to an XSD, you follow a specific XML Schema validation process. This involves creating both the XML instance document and its corresponding XSD, then linking them for validation.

The XSD Validation Process Steps:

  1. Create XML File: Develop your XML document containing the data.
  2. Create XML Schema Definition File: Write the XSD file that defines the structure and rules for your XML data.
  3. Link XML File with XSD File: Establish a connection within your XML document to its XSD schema.
  4. Check for Well-Formedness: Before validation, ensure both the XML and XSD files are well-formed (correct syntax, proper nesting, closing tags, quotes, etc.).
  5. Validate XML File: Use a parser or validator to check the XML document against the rules defined in the XSD.

Referencing XSD in Your XML Document

Linking an XML document to its XSD is done within the root element of the XML document, typically using namespaces. There are two main ways to reference an XSD:

A) Not using targetNamespace in XSD:

<rootElement xmlns:xsi=""
 xsi:noNamespaceSchemaLocation="example.xsd">
 <!-- XML content -->
</rootElement>

B) Using targetNamespace in XSD:

This is more common and involves defining a targetNamespace in your XSD. The XML instance document then uses this namespace.

<my:rootElement xmlns:my=""
 xmlns:xsi=""
 xsi:schemaLocation=" example.xsd">
 <!-- XML content -->
</my:rootElement>
  • xmlns:xsi="": This declaration introduces the XML Schema instance namespace, often conventionally prefixed with xsi. It indicates that you are connecting an XML Schema.
  • xsi:schemaLocation="usuallyURI example.xsd" or xsi:noNamespaceSchemaLocation="example.xsd": This attribute specifies the location of your schema. For schemaLocation, it's a pair: the first part is the namespace URI declared in the XSD's targetNamespace, and the second is the path to the actual .xsd file.

If your XSD uses a targetNamespace, you can make it the default namespace in your XML instance document using xmlns="someURI", removing the need for prefixes on elements belonging to that namespace. Alternatively, xmlns:myprefix can be used to assign a specific prefix.

Creating an XML Schema Definition (XSD) File

Building an XSD file involves defining its root element and setting up namespaces. Understanding these initial steps is key to developing a valid schema for your XML document structure definition.

The XSD Root Element: xs:schema

Every XSD file begins with the <xs:schema> root element. This element contains critical attributes:

  • xmlns:xs="": This attribute declares the namespace for elements and data types used within the schema itself (e.g., xs:element, xs:string). The prefix xs is a common convention.
  • targetNamespace="someURI": This is a unique URI that identifies the namespace to which the elements and attributes defined by this schema belong. This URI is used by XML instance documents to reference the schema.
  • elementFormDefault="qualified | unqualified": This attribute determines whether all elements defined in the XSD must be prefixed (qualified) in the XML instance document, or if only global elements need qualification (unqualified).

Here's an example of an XSD schema root:

<xs:schema xmlns:xs=""
 targetNamespace=""
 xmlns=""
 elementFormDefault="qualified">
 <!-- Schema definitions go here -->
</xs:schema>

In this example, xmlns="" sets the targetNamespace as the default for elements defined within this schema, meaning elements like Person will not need a prefix in the XML instance if elementFormDefault="qualified" is set.

Flashcards

1 / 79

Co je XML Schema Definition (XSD)?

Alternativa k DTD; popis struktury a dat XML dokumentu pomocí XML (soubor *.xsd) s využitím jmenných prostorů.

Tap to flip · Swipe to navigate

Understanding xs:simpleType and xs:complexType

In XSD, the definition of elements and attributes revolves around two fundamental types of content: xs:simpleType and xs:complexType. These are crucial for accurate XML data type definition.

xs:simpleType

An xs:simpleType defines elements or attributes that contain only text content and no child elements or attributes of their own. Examples include a person's age or a unit of measurement.

  • Elements: An element defined with simpleType has no attributes and no descendants. For instance, <age>36</age>.
  • Attributes: Attributes inherently use simpleType, such as age="36".

Basic Definition of an Element with xs:simpleType

To define an element using a simple type, you typically specify its name and type:

<xs:element name="element_name" type="..."/>

Common built-in xs:simpleType data types include:

  • xs:string: General text.
  • xs:decimal: A decimal number (e.g., 8.5).
  • xs:integer: An integer (e.g., 85).
  • xs:boolean: True/false or 0/1.
  • xs:date: Date format (YYYY-MM-DD).
  • xs:time: Time format (HH:MM:SS).

Other useful data types include xs:normalizedString, xs:token, xs:hexBinary, xs:anyURI (for links), and older DTD types like ID, IDREF, NMTOKEN.

Date and Time Data Types

XSD provides rich types for dates and times:

  • xs:date: Represents a date, e.g., <date>2010-11-08</date>. Can include UTC offset: <date>2010-11-08Z</date> or <date>2010-11-08+02:00</date>.
  • xs:time: Represents a time, e.g., <alarm>14:30:00</alarm>. Can include fractions of seconds and UTC offset.
  • xs:dateTime: Combines date and time, e.g., <beginning>2010-11-09T15:45:00+02:00</beginning>.
  • xs:duration: Represents a period of time, e.g., <cycle>P3M</cycle> (3 months) or <cycle>P2Y6M14DT10H</cycle> (2 years, 6 months, 14 days, 10 hours).

Defining Attributes with xs:simpleType

Attributes are defined similarly to elements but use <xs:attribute>:

<xs:attribute name="att_name" type="xs:..." use="..." default="..." fixed="..."/>
  • type: Uses the same data types as elements.
  • use: Specifies if the attribute is optional or required.
  • default: Provides a preset value if the attribute is omitted in the XML instance. This value can be changed.
  • fixed: Specifies a value that cannot be changed. The parser will ensure the attribute, if present, matches this value, or insert it if missing.

xs:complexType

An xs:complexType defines elements that can contain child elements, attributes, or both. This is used for more structured content.

Examples include:

  • Elements with only descendants: <inputs><firstname>John</firstname><surname>Black</surname></inputs>
  • Empty elements with attributes: <student id="12354"/>
  • Elements with text content and attributes: <notebook producer="HP">6320</notebook>
  • Elements with attributes and descendants: <customer name="John"><address>...</address></customer>

Content Models for xs:complexType

Within a complexType, you define the arrangement of its child elements using compositors:

  • xs:all: Child elements can appear in any order, and each must appear zero or one time. (Note: maxOccurs can only be 1 for xs:all children).
<xs:complexType>
<xs:all>
<xs:element name="firstname" type="xs:string"/>
<xs:element name="surname" type="xs:string"/>
</xs:all>
</xs:complexType>
  • xs:choice: Only one of the defined child elements can appear.
<xs:complexType>
<xs:choice>
<xs:element name="teacher" type="employee"/>
<xs:element name="student" type="student"/>
</xs:choice>
</xs:complexType>
  • xs:sequence: Child elements must appear in the exact order defined.
<xs:complexType>
<xs:sequence>
<xs:element name="firstname" type="xs:string"/>
<xs:element name="lastname" type="xs:string"/>
</xs:sequence>
</xs:complexType>

Occurrence Indicators

For elements within complexType, you can specify how many times they can appear:

  • minOccurs: The minimum number of occurrences (default is 1).
  • maxOccurs: The maximum number of occurrences (can be unbounded for unlimited).

Example: An owner element can appear one or many times.

<xs:element name="owner" type="xs:string" minOccurs="1" maxOccurs="unbounded"/>

Groups and Attribute Groups

To reuse common sets of elements or attributes, XSD provides:

  • xs:group: Groups a sequence, choice, or all of elements, which can then be referenced.
  • xs:attributeGroup: Groups a set of attributes for reuse across multiple elements.

These are useful for maintaining consistency and reducing redundancy in your schema.

Undefined Elements and Attributes

XSD allows for flexibility when you anticipate elements or attributes that aren't strictly defined in the schema:

  • xs:any: Allows for any valid XML element to appear at its location. minOccurs="0" makes it optional.
<xs:complexType>
<xs:sequence>
<xs:element name="processor" type="xs:string"/>
<xs:any minOccurs="0"/>
</xs:sequence>
</xs:complexType>
  • xs:anyAttribute: Allows for any valid XML attribute to appear on the element.
<xs:complexType>
<xs:sequence>
<xs:element name="producer" type="xs:string"/>
</xs:sequence>
<xs:anyAttribute/>
</xs:complexType>

Customizing Data Types with Restrictions

When standard XSD data types are not sufficient, you can define XML Schema custom data types using xs:restriction. This allows you to apply specific rules to element and attribute values.

<xs:element name="myelement" type="xs:string">
 <xs:simpleType>
 <xs:restriction base="xs:string">
 <xs:enumeration value="Value1"/>
 <xs:enumeration value="Value2"/>
 </xs:restriction>
 </xs:simpleType>
</xs:element>

Common data type restrictions include:

  • enumeration: A predefined list of possible values (e.g., Value1, Value2).
  • length: Exact number of characters or digits.
  • minLength: Minimum number of characters/digits.
  • maxLength: Maximum number of characters/digits.
  • minExclusive / maxExclusive: Specifies strict lower/upper bounds (value must be less than or greater than the specified value).
  • minInclusive / maxInclusive: Specifies inclusive lower/upper bounds (value must be less than or equal to or greater than or equal to the specified value).
  • fractionDigits: Maximum number of decimal places.
  • totalDigits: Exact number of digits (for numbers).
  • pattern: Defines a regular expression (regex) that the value must match.
  • whiteSpace: Specifies how whitespace characters (spaces, tabs, line feeds, carriage returns) are handled.

Using Patterns (Regular Expressions) in XSD

Regular expressions (regex or regexp) are powerful tools for defining specific XML data format patterns. They allow you to define sequences of characters that values must conform to.

  • [a-zA-Z0-9]{8}: Matches exactly 8 characters, which can be any uppercase letter, lowercase letter, or digit.
  • [abc]: Matches a single character that is 'a', 'b', or 'c'.
  • ([a-z])*: Matches zero or more lowercase letters.
  • ([a-z][0-9])+: Matches one or more occurrences of a lowercase letter followed by a digit.
  • 24|69: Matches either

Sign up to access full content

Create a free account to unlock all study materials, take interactive tests, listen to podcasts and more.

Create free account

Related topics