Skip to content
Bartlomiej Tartanus edited this page May 15, 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.

import java.io.ByteArrayInputStream
import java.nio.file.{Files, Paths}
import javax.xml.XMLConstants._
import javax.xml.transform.stream.StreamSource
import javax.xml.validation.SchemaFactory
import javax.xml.parsers.SAXParserFactory
import scala.xml.factory.XMLLoader
import scala.xml.parsing

val xsdPath = Paths.get("sitemap-v0.9.xsd")
val xsdContents = Files.readAllBytes(xsdPath)
val xsdStream = new StreamSource(new ByteArrayInputStream(xsdContents))
val schema = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI).newSchema(xsdStream)

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

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