XML validation ensures that an XML document strictly conforms to a predefined structural schema defined in XSD (XML Schema Definition).
While Python's standard library ElementTree parses XML rapidly, schema validation against XSD is best accomplished using the high-performance lxml library.
Below is a sample XML document alongside an XSD schema specifying that id and mark must be integers and name must be a string:
<!-- Define XML Data -->
<students>
<student>
<id>1</id>
<name>John Deo</name>
<mark>75</mark>
</student>
</students>
<!-- Define XSD Schema -->
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="students">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="student" maxOccurs="unbounded">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="id" type="xsd:integer"/>
<xsd:element name="name" type="xsd:string"/>
<xsd:element name="mark" type="xsd:integer"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>
To perform schema validation, install lxml via pip (`pip install lxml`) and execute the following script:
from lxml import etree
# Define XML data
xml_data = """
<students>
<student>
<id>1</id>
<name>John Deo</name>
<mark>75</mark>
</student>
</students>
"""
# Define XSD schema
xsd_data = """
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="students">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="student" maxOccurs="unbounded">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="id" type="xsd:integer"/>
<xsd:element name="name" type="xsd:string"/>
<xsd:element name="mark" type="xsd:integer"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>
"""
# Parse XML and XSD
xml_doc = etree.fromstring(xml_data)
xsd_doc = etree.XMLSchema(etree.fromstring(xsd_data))
# Validate XML
if xsd_doc.validate(xml_doc):
print("XML is valid.")
else:
print("XML is invalid.")
print(xsd_doc.error_log)
Validating XML against XSD schemas guarantees structural integrity and data consistency. Python's lxml library provides industry-standard performance for these checks.
Practice XML schema validation in our companion Jupyter Notebook:
Explore interactive code cells and test XSD schema validation using lxml.
View on GitHubAuthor & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.