Skip to content

Instantly share code, notes, and snippets.

@ramn
Created December 2, 2010 11:02
Show Gist options
  • Save ramn/725139 to your computer and use it in GitHub Desktop.
Save ramn/725139 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
}
}
@stuartrivero
Copy link

I haven't tried it but would using Try be more Scala?

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))
      true
    }).getOrElse(false)
  }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment