Skip to content
Aaron S. Hawley edited this page May 25, 2018 · 10 revisions

XML literals in your Scala code will not compile if the XML is not well-formed. However, there is no way for the Scala compiler to validate whether the XML conforms to an XML schema definition (XSD).

More often you'll be writing an application that is reading XML from a file. That file can either be well-formed or malformed. But even if it is well-formed XML, the XML may be invalid and not have the expected elements that were expected.

When XML parsed by scala-xml is malformed, it will throw errors that aren't entirely useful. One way to make sure your scala-xml code is operating on valid XML is to have the SAXParser validate it with an XSD. Here is an example using the XSD for site maps as published by the http://www.sitemaps.org project.

val schemaLang = javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI
val xsdFile = java.nio.file.Paths.get("sitemap-v0.9.xsd")
val readOnly = java.nio.file.StandardOpenOption.READ
val inputStream = java.nio.file.Files.newInputStream(xsdFile, readOnly)
val xsdStream = new javax.xml.transform.stream.StreamSource(inputStream)
val schema = javax.xml.validation.SchemaFactory.newInstance(schemaLang).newSchema(xsdStream)

val factory = javax.xml.parsers.SAXParserFactory.newInstance()
factory.setNamespaceAware(true)
factory.setSchema(schema)
val validatingParser = factory.newSAXParser()
val sitemap = new scala.xml.factory.XMLLoader[scala.xml.Elem] {
  override def parser = validatingParser
  override def adapter =
    new scala.xml.parsing.NoBindingFactoryAdapter
      with scala.xml.parsing.ConsoleErrorHandler

}.loadFile("sitemap.xml")
inputStream.close()
Clone this wiki locally