Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

xsd

I successfully read an XSD schema using org.eclipse.xsd.util.XSDResourceImpl 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 null as its type. It seems the imported schemas are not processed by XSDResourceImpl. 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

Update:
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?

like image 948
Pavel Gatnar Avatar asked Nov 09 '22 20:11

Pavel Gatnar


1 Answers

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();
like image 158
Pavel Gatnar Avatar answered Nov 15 '22 13:11

Pavel Gatnar