XSD Example

Welcome to The Coding College! In this article, we’ll walk through a complete XSD example, showing you how to define an XML Schema (XSD) and use it to validate an XML document. By the end of this guide, you’ll have a clear understanding of how to structure and enforce rules for your XML data using XSD.

What is XSD?

XSD (XML Schema Definition) is a language used to define the structure, content, and data types of an XML document. It ensures that your XML data adheres to a specific format and meets defined constraints.

Steps to Create and Use XSD

  1. Create an XML document that requires validation.
  2. Create an XSD file that defines the rules and structure of the XML document.
  3. Validate the XML against the XSD using an XML validator or tools like an online XSD validator, an XML editor, or programming libraries.

Example Scenario

Let’s create a schema for an XML document that represents information about books in a library.

XML Document: library.xml

<library>
  <book>
    <title>Introduction to XML</title>
    <author>John Doe</author>
    <year>2021</year>
    <price currency="USD">29.99</price>
  </book>
  <book>
    <title>Advanced XSD Techniques</title>
    <author>Jane Smith</author>
    <year>2023</year>
    <price currency="EUR">35.50</price>
  </book>
</library>

XSD Definition: library.xsd

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

  <!-- Root Element -->
  <xs:element name="library">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="book" maxOccurs="unbounded">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="title" type="xs:string"/>
              <xs:element name="author" type="xs:string"/>
              <xs:element name="year" type="xs:positiveInteger"/>
              <xs:element name="price">
                <xs:complexType>
                  <xs:simpleContent>
                    <xs:extension base="xs:decimal">
                      <xs:attribute name="currency" type="xs:string" use="required"/>
                    </xs:extension>
                  </xs:simpleContent>
                </xs:complexType>
              </xs:element>
            </xs:sequence>
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>

</xs:schema>

Explanation of the XSD

1. Root Element: <library>

  • The root element <library> contains a sequence of <book> elements.
  • The maxOccurs="unbounded" attribute allows an unlimited number of <book> elements.

2. Complex Type for <book>

  • Each <book> element contains:
    • <title>: A required string.
    • <author>: A required string.
    • <year>: A required positive integer.
    • <price>: A required element with both value (decimal) and an attribute (currency).

3. <price> with Attribute

  • The <price> element uses simple content to combine a value (xs:decimal) and an attribute (currency).

Validating the XML

Using Online Tools

Using Code (Python Example)

Here’s how to validate XML using Python with the lxml library:

from lxml import etree

# Load the XML and XSD files
xml_file = "library.xml"
xsd_file = "library.xsd"

# Parse the XML and XSD
with open(xml_file, 'r') as xml:
    xml_doc = etree.parse(xml)

with open(xsd_file, 'r') as xsd:
    xsd_doc = etree.parse(xsd)

# Validate the XML against the XSD
schema = etree.XMLSchema(xsd_doc)
is_valid = schema.validate(xml_doc)

if is_valid:
    print("The XML document is valid!")
else:
    print("The XML document is invalid!")
    print(schema.error_log)

Output

  • If the XML conforms to the XSD, the script will output:
The XML document is valid!
  • If the XML violates the XSD rules, the script will display error details.

Example of Invalid XML

Here’s an invalid XML that violates the XSD:

<library>
  <book>
    <title>Introduction to XML</title>
    <author>John Doe</author>
    <!-- Missing the <year> element -->
    <price>29.99</price>
  </book>
</library>

Validation Error:

  • The <year> element is missing, which is required by the XSD.

Key Benefits of XSD

  1. Data Integrity: Ensures the XML data adheres to a strict structure.
  2. Flexibility: Supports data types, attributes, and nested elements.
  3. Interoperability: Standardized validation for XML documents.

Conclusion

This example demonstrates how to define an XML schema (XSD) to validate the structure and data of an XML document. By using XSD, you can ensure your XML is consistent, accurate, and adheres to predefined rules. For more insights into XML, XSD, and other coding topics, visit The Coding College today!

Leave a Comment