1. Technology

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

By

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

Related Video
Replace a Dull Sky Using Photoshop Elements
  1. About.com
  2. Technology
  3. Delphi
  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

©2014 About.com. All rights reserved.