I defined a simple Xtext grammar that looks like this (simplified):
grammar org.xtext.example.mydsl.MyDsl with org.eclipse.xtext.common.Terminals generate myDsl "http://www.xtext.org/example/mydsl/MyDsl" import "http://www.eclipse.org/emf/2002/Ecore" as ecore System: 'Define System' ( 'Define Components' '{' components+=Component+ '}' ) 'End' ; Component: 'Component' name=ID 'Value' value=Double ';' ; Double returns ecore::EDouble: '-'? INT? '.' INT ;
The problem I like to solve is how can I convert a simple Java object to a valid xtext file?
To simplify my problem, let's say we create a list of components in Java:
List<Component> components = new ArrayList<Component>(); components.add(new Component("FirstComponent", 1.0)); components.add(new Component("SecondComponent", 2.0)); components.add(new Component("ThirdComponent", 3.0));
The output file that I like to create should look like this:
Define System Define Components { Component FirstComponent Value 1.0; Component SecondComponent Value 2.0; Component ThirdComponent Value 3.0; } End
It is important that this file is checked using the xtext grammar so that it is valid. Hope you have some ideas for me. Here are some of mine, but so far I donβt know how to implement them:
Idea # 1: I know how to read and write a file. In my head, one solution might look like this: I have a list in my Java code, now I like to write a file that looks like the output file above. Subsequently, I like to read this file and check grammar errors. How can i do this?
Idea # 2: If I assume that I would create an xml file from Java code using JDOM, I would like to do the same in xtext. Just define the parent "Define System" that ends with "End" (see My output file), and then add the child element "Define Components {" that ends with "}" and then add children to it, for example. "Component FirstComponent Value 1.0;". Hope this does not confuse :-)
Idea # 3: I could use a pattern like the following and add children between the braces "{" ... "}":
Define System Define Components { ... } End
Btw: I've already tried binding Xtext with a StringTemplate code generator , but this is another problem. Hope you have some ideas.