有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在XML文件中自动检测XSD模式文件?

我试图根据许多XSD文件验证XML文件。此时,我只能手动输入xsd模式。(我的意思是检查XML文件并查看XSD定义)。如何在任何XML文件中检测XSD模式文件

到目前为止,我尝试的是: //下面的方法根据多个xsd模式文件检查xml文件

public static void XSDValidation() throws SAXException, IOException, ParserConfigurationException {

    try {

        SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");

        Schema sch = schemaFactory.newSchema(new Source[] { new StreamSource(new FileInputStream("role-1.2.xsd")),
                new StreamSource(new FileInputStream("role-1.1.xsd")) });

        Validator validator = sch.newValidator();

        validator.validate(new StreamSource("role.xml"));

        System.out.println("INFO: Validation is done successfully.");

    } catch (Exception e) {
        System.out.println("ERROR: Validation is failed.");
    }
}

我使用DOM解析器和Java8

提前感谢所有的帮助

编辑: @kjhughes我不是简单地问

What's the best way to validate an XML file against an XSD file?

我的问题:如何检测XML文件中的XSD模式文件。例如,当我想验证包含b.xsd和c.xsd的a.xml时,我想自动并按真实顺序检测这些文件。我的意思是,如果XML首先使用c.xsd中的名称空间,那么应该检测它。在我的示例中,XSD模式文件及其顺序是通过检查XML内部来手动编写的


共 (1) 个答案

  1. # 1 楼答案

    您可以使用LSResourceResolver来解析模式依赖项。尽管您必须在这里指定所有依赖项,但它将代码与模式引用隔离开来

    schemaFactory.setResourceResolver(new LSResourceResolver(){
        @Override
        public LSInput resolveResource(String type, String namespaceURI, String publicId, String systemId, String baseURI) {
                // resovle the path to schema , read and return it.
        }
    
    });