Skip to content

Instantly share code, notes, and snippets.

@stphung
Forked from ramn/XmlSchemaValidator.scala
Created November 29, 2012 19:29
Show Gist options
  • Save stphung/4171272 to your computer and use it in GitHub Desktop.
Save stphung/4171272 to your computer and use it in GitHub Desktop.
XML Schema validator in Scala
import javax.xml.transform.stream.StreamSource
import javax.xml.validation.Schema
import javax.xml.validation.SchemaFactory
import javax.xml.validation.{Validator=>JValidator}
import org.xml.sax.SAXException
object Validator {
def main(args: Array[String]) {
require(args.size >= 2, "Params: xmlFile, xsdFile")
val result =
if (validate(args(0), args(1)))
"Validates!"
else
"Not valid."
println(result)
}
def validate(xmlFile: String, xsdFile: String): Boolean = {
try {
val schemaLang = "http://www.w3.org/2001/XMLSchema"
val factory = SchemaFactory.newInstance(schemaLang)
val schema = factory.newSchema(new StreamSource(xsdFile))
val validator = schema.newValidator()
validator.validate(new StreamSource(xmlFile))
} catch {
case ex: SAXException => println(ex.getMessage()); return false
case ex: Exception => ex.printStackTrace()
}
true
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment