-
Notifications
You must be signed in to change notification settings - Fork 92
XML validation
XML literals in your Scala code will not compile if the XML is not malformed. 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 an XML is parsed by scala-xml when it is malformed 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 = new java.io.FileInputStream("sitemap-v0.9.xsd")
val xsdStream = new StreamSource(xsdFile)
val schema = SchemaFactory.newInstance(schemaLang).newSchema(xsdStream)
val factory = SAXParserFactory.newInstance()
factory.setNamespaceAware(true)
factory.setSchema(schema)
val validatingParser = factory.newSAXParser()
val sitemap = new scala.xml.factory.XMLLoader[Elem] {
override def parser = validatingParser
override def adapter = new parsing.NoBindingFactoryAdapter with parsing.ConsoleErrorHandler
}.loadFile("sitemap.xml")