XML — Validation
Well-Formed vs Valid
- Well-formed: Follows XML syntax rules
- Valid: Conforms to a DTD or Schema
DTD (Document Type Definition)
<?xml version="1.0"?>
<!DOCTYPE note [
<!ELEMENT note (to, from, heading, body)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
<!ELEMENT heading (#PCDATA)>
<!ELEMENT body (#PCDATA)>
]>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me!</body>
</note>
XML Schema (XSD)
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="note">
<xs:complexType>
<xs:sequence>
<xs:element name="to" type="xs:string"/>
<xs:element name="from" type="xs:string"/>
<xs:element name="heading" type="xs:string"/>
<xs:element name="body" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
DTD vs Schema
| Feature | DTD | XSD |
|---|---|---|
| Syntax | Non-XML | XML |
| Data types | Limited | Full support |
| Namespace | No | Yes |
| Complexity | Simple | More complex |
Referencing a Schema
<?xml version="1.0"?>
<note xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="note.xsd">
<to>Tove</to>
</note>
Mini Practice
- Create a DTD for a simple document
- Create an XML Schema
- Validate XML against both
- Add constraints with Schema types
Up Next
Continue with Tree — understanding XML tree structure.
Related Topics
Frequently Asked Questions about Validation
What is Validation in XML?
Validation is a fundamental concept in XML. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Validation?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Validation.
Why is Validation important in XML?
Validation is essential for XML development. Understanding this concept will help you write better code and solve real-world problems more effectively.