Validate an XML File Against Multiple Schema Definitions

前端 未结 8 1545
囚心锁ツ
囚心锁ツ 2020-12-01 09:23

I\'m trying to validate an XML file against a number of different schemas (apologies for the contrived example):

  • a.xsd
  • b.xsd
  • c.xsd
8条回答
  •  栀梦
    栀梦 (楼主)
    2020-12-01 09:30

    Just in case, anybody still come here to find the solution for validating xml or object against multiple XSDs, I am mentioning it here

    //Using **URL** is the most important here. With URL, the relative paths are resolved for include, import inside the xsd file. Just get the parent level xsd here (not all included xsds).
    
    URL xsdUrl = getClass().getClassLoader().getResource("my/parent/schema.xsd");
    
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = schemaFactory.newSchema(xsdUrl);
    
    JAXBContext jaxbContext = JAXBContext.newInstance(MyClass.class);
    Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
    unmarshaller.setSchema(schema);
    
    /* If you need to validate object against xsd, uncomment this
    ObjectFactory objectFactory = new ObjectFactory();
    JAXBElement wrappedObject = objectFactory.createMyClassObject(myClassObject); 
    marshaller.marshal(wrappedShipmentMessage, new DefaultHandler());
    */
    
    unmarshaller.unmarshal(getClass().getClassLoader().getResource("your/xml/file.xml"));
    

提交回复
热议问题