Traversing the Project Tree

This example shows how to traverse the Project Tree for a specific item. This example uses the IProjectTree80 (FindItem, GetItemName, HiddenGroupName) property and methods.

 

function ScanTree()

        {

            try

            {

                alert("Click OK to find Vermont item by its path in the tree");

                var id = SGWorld.ProjectTree.FindItem("New England\\States\\Vermont");

                if(id!="")

                    alert("Found Vermont with id=" + id);

                else

                    alert("New England\\States\\Vermont does not exist in tree");

                // root is the first visible item in tree.

                var root = SGWorld.ProjectTree.GetNextItem("", 18 /* ItemCode.ROOT*/);

                // if the tree have hidden group, skip it.

                // find hidden group by its name. We could also check by HiddenGroupID, which is actually its parent id.

                if(SGWorld.ProjectTree.GetItemName(root) == SGWorld.ProjectTree.HiddenGroupName)

                    root = SGWorld.ProjectTree.GetNextItem(root,13 /* ItemCode.NEXT*/);

                var tree = BuildTreeRecursive(root, 1);

                alert(tree);

            }

            catch (ex)

            {

               alert("Unexpected error: " + ex.description);

            }

        }

 

        function BuildTreeRecursive(current, indent)

        {

            // build padding

            var padding = "";

            for (var i = 0; i < indent * 3; i++)

                padding += "-"

            var result = "";

            // iterate over all siblings of current node

            while (current)

            {

                // append node name to the tree string

                var currentName = SGWorld.ProjectTree.GetItemName(current);

                result += padding + currentName + "\r\n";

                // if current node is group, recursively build tree from its first child;

                if (SGWorld.ProjectTree.IsGroup(current))

                {

                    var child = SGWorld.ProjectTree.GetNextItem(current,11 /* ItemCode.CHILD */);

                    result += BuildTreeRecursive(child, indent + 1);

                }

                // move to next sibling

                current = SGWorld.ProjectTree.GetNextItem(current,13 /* ItemCode.NEXT*/);

            }

            return result;

        }