Mega Code Archive

 
Categories / Delphi / XML
 

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

Title: How to Create the !DocType and ?XML Elements using TXmlDocument Delphi component 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 "" (document type declaration) element and a "" 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,'') ; sl.Insert(0,'') ; sl.SaveToFile('c:\Test.xml') ; finally sl.Free; end; finally xmlDoc := nil; end; end; And here's the resulting XML: Node Text