XML Delphi

Title: Validate an XML Against a DTD Using TXMLDocument and Delphi
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:

Zarko

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.




With the above DTD, the XML section is valid.
To reference an external DTD file a DOCTYPE declaration can be added to the XML:



Zarko

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.



Zarko

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.