简体   繁体   中英

Validate xml against two schemas using java

I want to validate an xml file that has a schemalocation given in the root element without having this file localy. I think I got this to work but the problem is this xml contains another schema that is located on another element in the xml file and I can't find a way do define to schemas to validate a single file. Can someone help me here?

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

Also is the a way to get the variable UrlToSchema from the xml file?

You have to define an array of StreamSource to contain the list of xml schemas. you can refer the javadoc for this.

The code should look like this assuming that there are two xml schemas ie xsds

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

In you case, to read from the ulr, you can use below code.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM