1. Computing

Check if an XML Conforms to the Rules of a DTD

Validate an XML Against a Document Type Definition using TXMLDocument

By

xml dtd validation error

xml dtd validation error

A Document Type Definition (DTD) file can be used with an XML (Extensible Markup Language) file to specify the allowable structure and content of the XML document.

For an XML (section) defined as:

 <Language name="Delphi">
   <DeveloperName>Zarko</DeveloperName>
 </Language> 
A DTD file (named "developers.dtd" for example) can be created to specify valid tags and attributes. The purpose of a DTD is to define the structure of an XML document. It defines the structure with a list of legal elements.
 <!ELEMENT Language (DeveloperName)>
 <!ATTLIST Language name CDATA #REQUIRED>
 <!ELEMENT DeveloperName (#PCDATA)>
 
With the above DTD, the XML section is valid.

To reference an external DTD file a DOCTYPE declaration can be added to the XML:

 <?xml version="1.0"?>
 <!DOCTYPE note SYSTEM "developers.dtd">
 <Language name="Delphi">
   <DeveloperName>Zarko</DeveloperName>
 </Language> 
The above XML IS valid according to "developers.dtd".

The next XML is NOT valid according to "developers.dtd", because it is missing the required attribute "name" for the "language" tag.

 <?xml version="1.0"?>
 <!DOCTYPE note SYSTEM "developers.dtd">
 <Language>
   <DeveloperName>Zarko</DeveloperName>
 </Language> 

Programmatically Validate an XML Against a DTD using TXMLDocument

If you need to validate an existing XML document against a DTD, use the next procedure:
 uses xmldom, XMLIntf, XMLDoc;
 
 function ValidateXML(const xmlFile : TFileName) : boolean;
 var
   xmlDoc: TXMLDocument;
 begin
   result := false;
   xmlDoc := TXMLDocument.Create(nil) ;
   try
     xmlDoc.ParseOptions := [poResolveExternals, poValidateOnParse];
     try
       xmlDoc.LoadFromFile(xmlFile) ;
       xmlDoc.Active := true; //this will validate
       result := true;
     except
       on EX : EDOMParseError do
       begin
         ShowMessage('Invalid XML: ' + Ex.Message) ;
       end;
     end;
   finally
     xmlDoc := nil;
   end;
 end;
 
Note that if an XML is valid the function returns true. If the XML is not valid according to "its" DTD the function returns false and displays the validation error message.

Delphi tips navigator:
» Count MDI Children By Child Class Name in Delphi MDI Applications
« Quickly Load MDI Child Windows in Delphi MDI Applications - Avoid Resize Animation

©2014 About.com. All rights reserved.