首页 > 解决方案 > XSD 验证:发生异常时如何获取当前节点名称

问题描述

我正在做 xsd 验证,并在发生异常时尝试获取当前节点名称,但我得到了null

我已经尝试了下面的代码 -

import javax.xml.transform.stream.StreamSource
import javax.xml.validation.SchemaFactory
import org.xml.sax.SAXException
import scala.xml.Elem

object Validator {
 def main(args: Array[String]) {
  val result =
    if (validate("students.xml", "students.xsd"))
      "Valid!"
    else
      "Not valid."
  println(result)
}

def validate(xmlFile: String, xsdFile: String): Boolean = {
  val schemaLang = "http://www.w3.org/2001/XMLSchema"
  val factory = SchemaFactory.newInstance(schemaLang)
  val schema = factory.newSchema(new StreamSource(xsdFile))
  val validator = schema.newValidator()
  try {
    validator.validate(new StreamSource(xmlFile))
  } catch {
    case ex: SAXException => println(ex.getMessage)
      val msg:Elem= validator.getProperty("http://apache.org/xml/properties/dom/current-element-node").asInstanceOf[Elem]
      println("Current Node - "+msg)
      return false

    case ex: Exception => println(ex.getStackTrace)
  }
  true
 }
}

输出:

cvc-datatype-valid.1.2.1: 'Dinkar' is not a valid value for 'integer'.
Current Node - null
Not valid.

请帮我完成这件事。谢谢!

标签: xmlscalaxsdxsd-validation

解决方案


这是一个有趣的想法,但不可能scala.xml.Elemjavax.xml.validation.Validator验证失败时获得 ,因为javaxscala.xml. 如果可以用 召唤它会很好asInstanceOf[Elem],但它需要Elem在运行时更改一个类型的类。


推荐阅读