只是想知道是否有任何方法可以解析xsd文件和同时在原始xsd中导入的xsd,因此我可以直接访问导入的xsd中的元素。是否有任何框架使之成为可能?

只是我意思的一个例子

从我要解析的XSD:
<xsd:import namespace="..." schemaLocation="anotherFile.xsd"><xsd:element ref="anElement" />
从解析文件中导入的XSD
<xsd:element name="anElement"><xsd:simpleType><xsd:restriction base="xsd:string"> <xsd:enumeration value="THIS" /><xsd:enumeration value="IS" /> <xsd:enumeration value="THE" /><xsd:enumeration value="ELEMENTS" /><xsd:enumeration value="I" /><xsd:enumeration value="WANT" /><xsd:enumeration value=":-)" /></xsd:restriction></xsd:simpleType></xsd:element>
因此,我想要通过某种内联或其他方式解析原始xsd时访问导入的xsd中的元素:-)

这有可能吗?

最佳答案

是的,您只需要实现一个LSResourceResolver类即可读取指定的架构位置:

 /**
 * This function validates a DomResult. T
 *
 * @param domResult
 * @param schemaFile path to the schmea file to validate against.
 * @throws org.xml.sax.SAXException
 * @throws java.io.IOException
 *
 */
protected void validateDomResult(DOMResult domResult, String schemaFile) throws SAXException, IOException, Exception {

    Schema schema = createSchema(schemaFile);
    javax.xml.validation.Validator validator = schema.newValidator();
    ErrorHandler mySchemaErrorHandler = new LoggingErrorHandler();
    validator.setErrorHandler(mySchemaErrorHandler);
    DOMSource domSource = new DOMSource(domResult.getNode());
    validator.validate(domSource);
    if (((LoggingErrorHandler) mySchemaErrorHandler).isError()) {
        throw new Exception("Validation Error");
    }
}

/**
 *
 * @param baseSchemaFilePath
 * @return
 * @throws java.lang.Exception
 *
 */
protected Schema createSchema(String baseSchemaFilePath) throws Exception {

    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    LSResourceResolver resourceResolver = (LSResourceResolver) new LocalSchemaLSResourceResolver();
    factory.setResourceResolver(resourceResolver);
    Schema schema = factory.newSchema(new File(baseSchemaFilePath));

    return schema;
}

这是一个简单的LSResourceResolver实现,该实现在类路径的xsd目录中查找模式:
public class LocalSchemaLSResourceResolver implements LSResourceResolver{

    protected final Log logger = LogFactory.getLog(getClass());

    public LSInput resolveResource(String type, String namespaceURI, String publicId, String systemId, String baseURI) {

        LSInput input = new DOMInputImpl();
        try {
            FileInputStream fis = new FileInputStream(new File("classpath:xsd/" + systemId));

            input.setByteStream(fis);
            return input;
        } catch (FileNotFoundException ex) {
            logger.error("File Not found", ex);
            return null;
        }

    }
}

09-30 17:20
查看更多