Search code examples
enterprise-architect

Is it possible to programatically get the root node of an element?


I need to check if an element is contained in a given root node (model).

I'm currently querying the repository for all elements of type package with parent_ID=0, then getting the collection of elements in the root package and checking if the element is contained there.

function belongsToModel(element, model) {
var thequery = "SELECT * from t_object obj inner join t_package pkg on (obj.package_id = pkg.package_id) where obj.object_type = 'Package' and pkg.parent_ID=0"     
var thepackage;
var checkname;
var stereotypeElement;
var stereotypeElementsList = Repository.GetElementSet(thequery, 2);
var packageElement
var thePackageElement
var elementCollection

Session.Output("- Elements to process: " + stereotypeElementsList.Count);
for (var i = 0; i < stereotypeElementsList.Count; i++) {
    stereotypeElement = stereotypeElementsList.GetAt(i);
    var packageElement = Repository.GetPackageByID(stereotypeElement.PackageID);
    if (packageElement.Name == model){
        thePackageElement = stereotypeElement
        Session.Output("DEBUG packages: " + packageElement.Name + " element to check " + element.Name)
        elementCollection = thePackageElement.Elements;
        Session.Output("DEBUG Element Count: " + elementCollection.Count)
        checkname = elementCollection.GetByName(element.Name) 
        if (checkname != undefined){
            Session.Output("DEBUG element found: " + checkname.Name)
        }
    }
}
return checkname
}

However, this is not working and it really feels like a very rough workaround.

Is there any straightforward ways of checking this that I've missed?

Thank you!


Solution

  • I wonder why you make things that complicated. Just traverse the packageid of an element until you reach that with a zero-parent. There you are.

    Something like (no specific language):

    ptr = element.packageId
    while ptr != 0 {
      root = ptr
      ptr = repository.getPackageById(ptr).parentId
    }
    

    root will finally hold the id of the root package.