Valid XML

An XML file is valid, when well formed and conforms to the rules defined in the DTD or schema.

A DTD file used to define the structure of an XML file

The following file "message.dtd" is a DTD file:

<!DOCTYPE message [ <!ELEMENT message (from,to,title,text)> <!ELEMENT from (#PCDATA)> <!ELEMENT to (#PCDATA)> <!ELEMENT title (#PCDATA)> <!ELEMENT text (#PCDATA)> ]>

The structure of an XML file can also be defined by a schema.

This option is recommended by W3C.

The following file "message.xsd" is a file type to validate an XML schema.

<xs:element name="message"> <xs:complexType>     <xs:sequence>         <xs:element name="from" type="xs:string"/>         <xs:element name="to" type="xs:string"/>         <xs:element name="title" type="xs:string"/>         <xs:element name="text" type="xs:string"/>     </xs:sequence> </xs:complexType> </xs:element>

To tell the XML file DTD file must validate an XML file to be valid, there is the policy:

<!DOCTYPE note SYSTEM "message.dtd">

To validate against a schema is exactly the same but the file will be an outline, with an "xsd"

<!DOCTYPE note SYSTEM "message.xsd">

Thus our valid XML would look like:

<?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE note SYSTEM "mensaje.dtd"> <messages>     <message>         <from>James</from>         <to>Peter</to>         <title>Meeting</title>         <text>Remember our meeting</text>     </message>
</messages>

Our example XML valid against the schema "message.xsd"

<?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE note SYSTEM "mensaje.xsd"> <messages>     <message>         <from>James</from>         <to>Peter</to>         <title>Meeting</title>         <text>Remember our meeting</text>     </message> </messages>