使用 org.eclipse.xsd.util.XSDResourceImpl 阅读 XSD

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

我使用 org.eclipse.xsd.util.XSDResourceImpl 成功读取了 XSD 模式并处理了所有包含的 XSD 元素、类型、属性等
但是当我想处理对导入模式中声明的元素的引用时,我得到 null 作为它的类型。 XSDResourceImpl 似乎没有处理导入的模式。 有什么想法吗?

    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

更新:
我使导入的 XSD 无效,但没有例外。这意味着它真的没有被解析。有没有办法强制加载导入的 XSD 和主要的?

你能试试类似的方法吗,手动解析类型:

final XSDResourceImpl rsrc = new XSDResourceImpl(URI.createFileURI(xsdFileWithPath));
rsrc.load(new HashMap());
final XSDSchema schema = rsrc.getSchema();
for (Object content : schema.getContents())
{
    if (content instanceof XSDImport)
    {
        XSDImport xsdImport = (XSDImport) content;
        xsdImport.resolveTypeDefinition(xsdImport.getNamespace(), "");
    }
}

你可以看看here。特别是在这种方法中:

   private static void forceImport(XSDSchemaImpl schema) { 
        if (schema != null) { 
            for (XSDSchemaContent content: schema.getContents()) { 
                if (content instanceof XSDImportImpl) { 
                    XSDImportImpl importDirective = (XSDImportImpl)content; 
                    schema.resolveSchema(importDirective.getNamespace()); 
                } 
            } 
        } 
    } 

有一个重要的技巧可以自动处理 importsincludes。您必须使用 ResourceSet 来读取主 XSD 文件。

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

然后在处理元素、属性或模型组之前,您必须使用:

elem = elem.getResolvedElementDeclaration();
attr = attr.getResolvedAttributeDeclaration();
grpdef = grpdef.getResolvedModelGroupDefinition();