Forum Discussion
Scarabanza
10 years agoNew Contributor
Shortly after posting my question, I found an answer. Isn't that always the way.
My solution is similar to what you have posted, but includes an error handler class to ensure all errors are reported on. My Groovy isn't very groovy, so this might not be the best way of coding it. I have also edited the code below to remove code that was specific to what I'm trying to do.
My solution is similar to what you have posted, but includes an error handler class to ensure all errors are reported on. My Groovy isn't very groovy, so this might not be the best way of coding it. I have also edited the code below to remove code that was specific to what I'm trying to do.
import javax.xml.XMLConstants
import javax.xml.transform.stream.StreamSource
import javax.xml.validation.SchemaFactory
import org.xml.sax.ErrorHandler
import org.xml.sax.SAXException
import org.xml.sax.SAXParseException
// Define a class to handle XML validation errors
class LoggingErrorHandler implements ErrorHandler {
def xmlErrorMessages
public void warning(SAXParseException ex) {
xmlErrorMessages += ex.message
xmlErrorMessages += "\n"
}
public void error(SAXParseException ex) {
xmlErrorMessages += ex.message
xmlErrorMessages += "\n"
}
public void fatalError(SAXParseException ex) {
xmlErrorMessages += ex.message
xmlErrorMessages += "\n"
}
}
// Validate the incoming message against the schema
def incomingXml = mockRequest.requestContent
def factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI)
def schema = factory.newSchema(new StreamSource(new FileReader("Schema.xsd")))
def validator = schema.newValidator()
def errorHandler = new LoggingErrorHandler()
validator.errorHandler = errorHandler
validator.validate(new StreamSource(new StringReader(incomingXml)))
if (errorHandler.xmlErrorMessages != "") {
// Do things here to deal with/report the errors
}
// Remainder of code to do things with a valid XML message