You are here:About>Computing & Technology>Delphi Programming> Coding Delphi Applications> Delphi Tips and Tricks> Delphi 2006 Tips> How to Create the !DocType and ?XML Elements using TXmlDocument Delphi component
About.comDelphi Programming
Newsletters & RSSEmail to a friendSubmit to Digg

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

From Zarko Gajic,
Your Guide to Delphi Programming.
FREE Newsletter. Sign Up Now!

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

 All Topics | Email Article | | |
Advertising Info | News & Events | Work at About | SiteMap | Reprints | HelpOur Story | Be a Guide
User Agreement | Ethics Policy | Patent Info. | Privacy Policy©2008 About, Inc., A part of The New York Times Company. All rights reserved.