Mega Code Archive

 
Categories / Delphi / Examples
 

Treerecurse

//create an XML DOM doc variable //load an XML file into the XML DOM doc //call the function to recursively iterate through all tree nodes: so //begin at the beginning, setting up pointers //to the root nodes of both the DOM tree and //the TreeView tree... //get the DOM tree's root node DOMnodePtrRoot := xmlDoc.childNodes.Item[0]; //make sure the TreeView is 'clean' //(with no nodes) //before working with it... TreeView.Items.Clear; //create a new TreeView tree's root node TVnodePtrRoot := AddTreeViewRootNode; TreeWalk(xmlDoc, DOMnodePtrRoot); DOMTreeToTreeView(xmlDoc, DOMnodePtrRoot, TVnodePtrRoot); /////////////////////////////////////////////////////////////// procedure TMainForm.TreeWalk(xmlDoc: IXMLDOMDocument; currDOMnodePtr: IXMLDOMNode); //a recursive procedure to iterate through every one of the nodes on a tree... //THIS DOES NOTHING -use as a foundation of something useful... var DOMnodePtr: IXMLDOMNode; nodeText: String; begin if (currDOMnodePtr.hasChildNodes) then begin DOMnodePtr := currDOMnodePtr.firstChild; repeat if (not(DOMnodePtr = nil)) then begin //filter out any nodes that are not 'element' type nodes if (DOMNodePtr.nodeType = NODE_ELEMENT) then begin nodeText := DOMnodePtr.nodeName; //ShowMessage(nodeText); TreeWalk(xmlDoc, DOMnodePtr); end; end; DOMnodePtr := DOMnodePtr.nextSibling; until (DOMnodePtr = nil); end; end; /////////////////////////////////////////////////////////////// procedure TMainForm.DOMTreeToTreeView(xmlDoc: IXMLDOMDocument; currDOMnodePtr: IXMLDOMNode; currTVnodePtr: TTreeNode); //recursively iterate through every one of the nodes on a DOM tree, creating nodes on //a TreeView tree that exactly reflect the structure of the DOM tree as we go, also //copying data from the DOM tree nodes to the TreeView tree nodes... //assume that the TreeView is global at this point... //-wrapping your head around this very succinct piece of code is not made any //easier by the fact that that the methods pertaining to a 'DOM node' are not //at all similar to the methods pertaining to a TreeView node... var DOMnodePtr: IXMLDOMNode; TVnodePtr: TTreeNode; nodeNameText: String; begin if (currDOMnodePtr.hasChildNodes) then begin DOMnodePtr := currDOMnodePtr.firstChild; repeat if (not(DOMnodePtr = nil)) then begin //filter out any nodes that are not 'element' type nodes if (DOMNodePtr.nodeType = NODE_ELEMENT) then begin nodeNameText := DOMnodePtr.nodeName; TVnodePtr := TreeView.Items.AddChild(currTVnodePtr, nodeNameText); DOMTreeToTreeView(xmlDoc, DOMnodePtr, TVnodePtr); end; end; DOMnodePtr := DOMnodePtr.nextSibling; until (DOMnodePtr = nil); end; end;