Loading an XML Document into the DOM - Code Explained
(Page 2 of 4 )
The aim of the program is to make it easy for us to manipulate XML documents. This process starts by loading or opening up an XML document. Naturally this will be the first step that this code will take.
Below is the procedure that does just that. The first part of this procedure defines an initial path for the application using the application.exename function:
procedure TForm1.Button1Click(Sender: TObject);
begin
od.InitialDir := ExtractFilePath (Application.ExeName);
Then we execute the opendialog component. This component will open up a dialog window that will enable you to choose an XML file to open:
if od.Execute then
begin
Once you've selected a file, you load it into the xmldocument component. The file, up to this point, would have been stored in the opendialog components filename property.
xd.LoadFromFile(od.FileName);
The next line of code clears the treeview control in which we want to load the XML document:
tv.Items.Clear;
Then we call the DOMShow procedure that actually does the job of loading the XML document into the relevant treeview together with its structure:
DOMShow (xd.DocumentElement, nil);
tv.FullExpand;
end;
end;
The DOMShow procedure is at the heart of the entire program. It is responsible for loading, reading and organizing the structure of the XML document. It is also responsible for showing it in the treeview control:
procedure TForm1.DOMShow(Anode: IXMLNode; TNode: TTreeNode);
First, we define some variables that we are going to need throughout this procedure:
var
I: Integer;
NTNode: TTreeNode;
NText: string;
AttrNode: IXMLNode;
begin
We then skip text nodes and other special cases:
if not (Anode.NodeType = ntElement) then
Exit;
Next: Adding Nodes >>
More Delphi-Kylix Articles
More By David Web