I need to validate xml file by xsd, and parse xml if it possible. I have the next example:
import java.io.FileInputStream
import javax.xml.XMLConstants
import javax.xml.parsers.SAXParserFactory
import javax.xml.transform.stream.StreamSource
import javax.xml.validation.SchemaFactory
import org.xml.sax.SAXParseException
import org.xml.sax.helpers.DefaultHandler
import scala.util.Try
import scala.xml.XML
object XMLTup extends App {
val schema = {
val factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI)
val xsdStream = new FileInputStream("xsd.xsd")
val schema = factory.newSchema(new StreamSource(xsdStream))
xsdStream.close()
schema
}
val saxParser = {
val f = SAXParserFactory.newInstance()
f.setNamespaceAware(true)
f.setSchema(schema)
f.newSAXParser()
}
//DOESN'T WORK
val xml1 = new FileInputStream("xml.xml")
println {
Try{XML.withSAXParser(saxParser).load(xml1)}
}
xml1.close()
//WORKS
val xml2 = new FileInputStream("xml.xml")
val handler = new DefaultHandler() {
override def error(ex: SAXParseException) {
println("Validation Error!")
}
}
saxParser.parse(xml2, handler)
xml2.close()
}
When I use scala XML (DOESN'T WORK), I got Success and haven't validation error, but the next code (WORKS) I got "Validation Error" message. Why is it happend? How can I validate XML by XSD with scala XML class?
No comments:
Post a Comment