Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用java根据两种模式验证xml_Java_Xml_Validation - Fatal编程技术网

使用java根据两种模式验证xml

使用java根据两种模式验证xml,java,xml,validation,Java,Xml,Validation,我想验证一个xml文件,该文件在根元素中具有给定的schemalocation,而不具有本地文件。我想我已经做到了,但问题是这个xml包含另一个模式,它位于xml文件中的另一个元素上,我找不到一种方法来定义模式来验证单个文件。有人能帮我吗 SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = schemaFactory.newSche

我想验证一个xml文件,该文件在根元素中具有给定的schemalocation,而不具有本地文件。我想我已经做到了,但问题是这个xml包含另一个模式,它位于xml文件中的另一个元素上,我找不到一种方法来定义模式来验证单个文件。有人能帮我吗

SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = schemaFactory.newSchema(new URL(UrlToSchema));
Validator validator = schema.newValidator();
validator.validate(new StreamSource(xmlFile));

这也是从xml文件中获取变量UrlToSchema的一种方法?

您必须定义一个
StreamSource
数组来包含xml模式列表。 对此,您可以参考

假设有两个xml模式(即XSD),代码应该是这样的

    StreamSource[] xsdSources = new StreamSource[2]; 
    FileInputStream fis1 = new FileInputStream("schema1.xsd"); 
    sources[0] = new StreamSource(fis1); 
    FileInputStream fis2 = new FileInputStream("schema2.xsd"); 
    sources[1] = new StreamSource(fis2); 
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); 
    Schema schema = schemaFactory.newSchema(xsdSources);
    Validator validator = schema.newValidator();
    validator.validate(new StreamSource(xmlFile)); 
在您的情况下,要读取ulr,可以使用以下代码

InputStream fis1 = new URL("http://www.somesite.com/schema1.xsd").openStream();
sources[0] = new StreamSource(fis1); 

这需要我在验证xml文件之前下载模式文件。我想使用xml文件中schemaLocation中定义的URL来验证文件。您也可以使用URL读取并将其存储在StreamSource中。谢谢,现在我只需要一种方法从xml文件中获取URL进行解析,这样我就不必为每种类型的xml文件硬编码URL。您可以简单地解析xml文件以获取url和其他内容,但在解析之前需要进行验证。由于XSD位于其他位置,因此需要提供。但是,您可以维护一个常量文件来维护xsd URL。