On 2013-21-05 10:12, Erick Fonseca wrote:
> Is there a specific way to get the root node from a Resource? Currently
> I'm doing
>
> resource.getContents().get(0)
>
>
> But I feel it's weird to get the whole content list if I just want the
> root.
You are doing it right.
A Resource is just more general than the use case of containing a parse
result.
which means that the user gets to see confusing stack traces for the
following errors
Resource is empty
Resource is multi-rooted
Resource doesn't contain MyRoot
usually resulting from a file name typo, but sometimes through
application defects.
I've taken to coding at least
for (EObject eObject : resource.getContents()) {
if (eObject instanceof MyRoot) {
doSomethingWith((MyRoot)eObject);
}
else {
some error
}
}
Regards
Ed Willink
On 21/05/2013 18:12, Erick Fonseca wrote:
> Is there a specific way to get the root node from a Resource?
> Currently I'm doing
>
> resource.getContents().get(0)
>
>
> But I feel it's weird to get the whole content list if I just want the
> root.
Hallvard Traetteberg Messages: 539 Registered: July 2009 Location: Trondheim, Norway
Senior Member
On 21.05.13 22.41, Ed Willink wrote:
>
> (MyRoot)resource.getContents().get(0)
>
> which means that the user gets to see confusing stack traces for the
> following errors
> Resource is empty
> Resource is multi-rooted
> Resource doesn't contain MyRoot
> usually resulting from a file name typo, but sometimes through
> application defects.
>
> I've taken to coding at least
>
> for (EObject eObject : resource.getContents()) {
> if (eObject instanceof MyRoot) {
> doSomethingWith((MyRoot)eObject);
> }
> else {
> some error
> }
> }
Yes, this is in general a lot better, since with Xtext-based DSLs it is
common to derive other models, and your particular root may not always
be the first element in such a case. I wish EcoreUtil had a method
<T> T getRoot(Class<T> clazz, boolean throwError) that did this, so it
was easy for everybody to start using this coding style.