Skip to content

Instantly share code, notes, and snippets.

@bond-
Last active December 14, 2015 21:19
Show Gist options
  • Save bond-/5150562 to your computer and use it in GitHub Desktop.
Save bond-/5150562 to your computer and use it in GitHub Desktop.
XSDValidations.groovy
def xsdFiles = []
//create input stream for common xsd
def common = new StreamSource(new FileInputStream("common.xsd"))
xsdFiles.add(common)
def common1 = new StreamSource(new FileInputStream("common1.xsd"))
xsdFiles.add(common1).
.
.
def common100 = new StreamSource(new FileInputStream("common100.xsd"))
xsdFiles.add(common100)//here, common1...100.xsd are imported in sample.xsd. so, common1..100.xsd must be before sample.xsd
def sample = new StreamSource(new FileInputStream("sample.xsd"))
xsdFiles.add(sample)
//at the end of this line, xsdFiles should contain in the following order
//xsdFiles = [common1.xsd, common2.xsd....common100.xsd,sample.xsd]
//Parse xml content
def xml = new XmlSlurper().parse("sample.xml")
validateXML(xsdFiles,xml)
/**
* Validates and throws SAXException if validation fails
* @param xsdFiles which should be consider while validating xml
* @param XMLContent current parsing xml content
* @throws SAXException
*/
static void validateXML(def xsdFiles,String XMLContent) throws SAXException{
def factory = XMLSchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI)
def schema = factory.newSchema((Source[])xsdFiles.toArray())
def validator = schema.newValidator()
validator.validate(new StreamSource(new StringReader(XMLContent)))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment