Creating Models, Packages, and Elements

The API allows you to create SPARX objects (Packages and Elements) in a model. An example use case would be a tool that exports requirements from a database and creates requirement elements in your model (or vise versa).

package tech.otter.EAUtil;

import org.sparx.Element;
import org.sparx.Package;
import org.sparx.Repository;

import java.text.SimpleDateFormat;
import java.util.Date;

public class Test {

    public static void main(String[] args) {
        String connection = new MySQLConnectionBuilder().load(System.getenv()).toString();

        log("===== Start =====");
        Repository r = new org.sparx.Repository();
        if(!r.OpenFile(connection)) {
            System.err.println("Connection failed: " + r.GetLastError().toString());

        log("Repository Opened");
        r.GetModels().forEach(p -> log("Model: " + p.GetName()));
        Package pParent = r.GetModels().AddNew("My New Model", "");
        Package pChild = pParent.GetPackages().AddNew("My Child Model", "");
        Element e = pChild.GetElements().AddNew("MyClass", "Class");
        log("===== Finish ====");

    private static SimpleDateFormat format = new SimpleDateFormat("mm:ss.SSS");
    private static void log(Repository repository) {
        log("Repository: " + repository.GetInstanceGUID());
        repository.GetModels().forEach(p -> log(4, p));
    private static void log(int level, Package model) {
        log("Model: " + model.GetName());
        model.GetPackages().forEach(p -> log(level+2, p));
        model.GetElements().forEach(e -> log(level+2, e));
    private static void log(int level, Element element) {
        log("Element: " + element.GetName());
        element.GetElements().forEach(e -> log(level+2, e));
    private static void log(String message) {
        log(0, message);
    private static void log(int level, String message) {
        String spacer = new String(new char[level]);
        System.out.println(format.format(new Date()) + ": " + spacer + message);
Element Creation Example

A few important things to note:

  1. Models represent your “Root” packages.
  2. Things are added in a weird way- by accessing a collection of that type of object (e.g. Repository#GetModels()) and calling Collection<>#AddNew().
  3. Once you have created an object, you need to call #Update() on its parent. Order does matter. Not sure why.