Pavel Gatnar Pavel Gatnar - 1 year ago 89
Java Question

Read XSD using org.eclipse.xsd.util.XSDResourceImpl

I successfully read an XSD schema using

and process all contained XSD elements, types, attributes etc.

But when I want to process a reference to an element declared in the imported schema, I get
as its type. It seems the imported schemas are not processed by
Any idea?

final XSDResourceImpl rsrc = new XSDResourceImpl(URI.createFileURI(xsdFileWithPath));
rsrc.load(new HashMap());
final XSDSchema schema = rsrc.getSchema();
if (elem.isElementDeclarationReference()){ //element ref
elem = elem.getResolvedElementDeclaration();
XSDTypeDefinition tdef = elem.getType(); //null for element ref


I made the imported XSD invalid, but get no exception. It means it is really not parsed. Is there any way to force loading imported XSD together with the main one?

Answer Source

There is one important trick to process imports and includes automatically. You have to use a ResourceSet to read the main XSD file.

import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.xsd.util.XSDResourceFactoryImpl;
import org.eclipse.xsd.util.XSDResourceImpl;
import org.eclipse.xsd.XSDSchema;

static ResourceSet resourceSet;
XSDResourceFactoryImpl rf = new XSDResourceFactoryImpl();
Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap().put("xsd", rf);
resourceSet = new ResourceSetImpl();
resourceSet.getLoadOptions().put(XSDResourceImpl.XSD_TRACK_LOCATION, Boolean.TRUE);
XSDResourceImpl rsrc = (XSDResourceImpl)(resourceSet.getResource(uri, true));
XSDSchema sch = rsrc.getSchema();

Then before processing an element, an attribute or a model group you have to use this:

elem = elem.getResolvedElementDeclaration();
attr = attr.getResolvedAttributeDeclaration();
grpdef = grpdef.getResolvedModelGroupDefinition();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download