2016-03-07 103 views
0

我用Xtext定義了一個DSL。假設它看起來像這樣:Xtext:將模型導出爲XMI/XML

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' 
; 

在生成的基於我的DSL的Eclipse IDE中,我實現了一個模型。假設它看起來像下面這樣:

House MyHouse 
    height 102.5 
    width 30.56 
end House 

Car MyCar 
    maxSpeed 190 
    brand "mercedes" 
end Car 

我現在想要將該模型導出爲XMI或XML文件。

我想這樣做的原因是,我有另一個工作流程,它允許我使用XMI/XML文件實時更改模型參數。因此,不必重新定義我的模型,我可以將XML/XMI文件傳遞給工作流程,這會自動執行此操作。

簡短示例:DSL允許定義組件HouseCarHouse允許參數widthheight,Car允許參數maxSpeedbrand(參見上面的語法)。

所以在我所說的工作流程中,參數會隨着不同的值而改變。例如,生成的XML我要找應該是這樣的:

<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> 

我怎樣才能導出我的模型作爲XMI/XML?

回答

1

我最終找到了一個解決方案。下面的代碼出口的* .xmi文件,就像在我的開場白後要求:

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(); 
    } 
} 
1

只是約翰的回答評論: 在Eclipse IDE從未使用MyLanguageStandaloneSetup,注射器的情況下必須通過的激活劑進行訪問一個UI插件:MyLanguageActivator.getInstance()。getInjector(MyLanguageActivator.COM_MYCOMPANY_MYLANGUAGE)。

調用MyLanguageStandaloneSetup.createInjectorAndDoEMFRegistration將創建一個與Eclipse使用的不同的Injector新實例。它也可以打破EMF註冊管理機構的狀態。

+0

非常感謝您的評論!雖然我成功導入MyLanguageActivator,但在運行時會出現'NoClassDefFoundError'。你知道爲什麼發生這種情況嗎? – John

+0

你如何運行導出?如果在Eclipse內部,您應該將代碼放在UI插件中才能訪問激活器。如果你不在外面,你可以把它放在一個語言項目中,並使用獨立的設置。 –