Search code examples
javaxmlxtextxmi

Xtext: Export model as XMI/XML


I have defined a DSL with Xtext. Let's say it looks like this:

Model:
    components+=Component*
;

Component:
    House | Car
;

House:
    'House' name=ID
    ('height' hubRadius=DOUBLE)? &
    ('width' hubRadius=DOUBLE)?
    'end' 'House'
;

Car:
    'Car' name=ID
    ('maxSpeed' hubRadius=INT)? &
    ('brand' hubRadius=STRING)?
    'end' 'Car'
;

In the generated Eclipse IDE, which is based on my DSL, I implemented a model. Let's say it looks like the following:

House MyHouse
    height 102.5
    width 30.56
end House

Car MyCar
    maxSpeed 190
    brand "mercedes"
end Car

I now would like to export that model as an XMI or XML file.

The reason I want to do this is, that I have another workflow, which allows me to change the model parameters on the fly, using an XMI/XML file. So instead of redefining my model, I can just pass the XML/XMI file to the workflow, which does this automatically.

Short example: The DSL allows defining the components House and Car. The House allows the parameters width and height, the Car allows the parameters maxSpeed and brand (see grammar above).

So in my workflow I was talking about, the parameters will be changed with different values. For example the generated XML I am looking for would look like this:

<model>
    <component name='House'>
        <param name='height'>102.5</param>
        <param name='width'>30.56</param>
    </component>
    <component name='Car'>
        <param name='maxSpeed'>190</param>
        <param name='brand'>mercedes</param>
    </component>
</model>

How can I export my model as XMI/XML?


Solution

  • I finaly found a solution. The following code exports an *.xmi file like requested in my opening post:

    private void exportXMI(String absuloteTargetFolderPath) {
        // change MyLanguage with your language name
        Injector injector = new MyLanguageStandaloneSetup()
                .createInjectorAndDoEMFRegistration();
        XtextResourceSet resourceSet = injector
                .getInstance(XtextResourceSet.class);
    
        // .ext ist the extension of the model file
        String inputURI = "file:///" + absuloteTargetFolderPath + "/MyFile.ext";
        String outputURI = "file:///" + absuloteTargetFolderPath + "/MyFile.xmi";
        URI uri = URI.createURI(inputURI);
        Resource xtextResource = resourceSet.getResource(uri, true);
    
        EcoreUtil.resolveAll(xtextResource);
    
        Resource xmiResource = resourceSet
                .createResource(URI.createURI(outputURI));
        xmiResource.getContents().add(xtextResource.getContents().get(0));
        try {
            xmiResource.save(null);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }