1. Home
  2. Computing & Technology
  3. Delphi Programming

How to Create the !DocType and ?XML Elements using TXmlDocument Delphi component

By , About.com Guide

Delphi's TXmlDocument component can be used to either read (and process) an existing XML document or to construct a new, empty XML document.

To add nodes to a XML, you can use the "AddChild" method or the "CreateElement" methods - the result is the IXMLNode interface you then use to add leaf nodes, apply attributes, etc.

One of the requirements for a valid XML is that it provides a "<!DOCTYPE ... >" (document type declaration) element and a "<?xml ... >" element, for example.

Unfortunately, Delphi's implementation of the TXMLDocument component, which basically uses Microsoft XML parser by default, does not provide a way to add a node of the "ntDocType" (TNodeType type).

One of the solutions to this problem is to manually add required nodes by accessing the XML property of the TXmlDocument, as it is a TStrings object.

Firstly, construct your XML document using AddChild methods.
Secondly, assign the resulting XML to a TStringList object. Then use methods of the TStringList (like Insert, Add) to add additional "elements" and "nodes" to the XML string.
Finally, save the XML contained in the string list to a file...

Here's an example:

var
   sl : TStringList;
   xmlDoc : TXMLDocument;
   iNode : IXMLNode;
begin
   xmlDoc := TXMLDocument.Create(nil) ;
   try
     xmlDoc.Active := true;

     iNode := xmlDoc.AddChild('leaf') ;
     iNode.Attributes['attrib1'] := 'value1';
     iNode.Text := 'Node Text';

     sl := TStringList.Create;
     try
       sl.Assign(xmlDoc.XML) ;

       sl.Insert(0,'<!DOCTYPE ns:mys SYSTEM "myXML.dtd">') ;
       sl.Insert(0,'<?xml version="1.0"?>') ;

       sl.SaveToFile('c:\Test.xml') ;
     finally
       sl.Free;
     end;

   finally
     xmlDoc := nil;
   end;
end;
And here's the resulting XML:
<?xml version="1.0"?>
<!DOCTYPE ns:mys SYSTEM "myXML.dtd">
<leaf attrib1="value1">Node Text</leaf>

Delphi tips navigator:
» Filtering TShellTreeView
« How to Draw Custom Text on a Form's Caption Bar

More Delphi Programming Quick Tips
Explore Delphi Programming
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. Delphi Programming
  4. Coding Delphi Applications
  5. Delphi Tips and Tricks
  6. Delphi 2006 Tips
  7. How to Create the !DocType and ?XML Elements using TXmlDocument Delphi component

©2009 About.com, a part of The New York Times Company.

All rights reserved.