xml - 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.
请帮我完成这件事。谢谢!
解决方案
这是一个有趣的想法,但不可能scala.xml.Elem
从javax.xml.validation.Validator
验证失败时获得 ,因为javax
对scala.xml
. 如果可以用 召唤它会很好asInstanceOf[Elem]
,但它需要Elem
在运行时更改一个类型的类。
推荐阅读
- javascript - Babel:模块解析失败(可能是由于导入元)
- java - 返回时将 JsonObject 解构为 GraphQL 类型
- python - 如何在 Django 缓存数据库中存储变量
- ios - 如何创建一个返回多次发射的可观察对象的函数?
- javascript - node.js 上的 Heroku 应用程序无法连接到 Heroku Postgre
- typescript - 使用带有泛型的 reduceRight 键入管道 compose 函数
- python - 清除根小部件的所有小部件
- javascript - Nodejs 错误:监听 EADDRINUSE:地址已在使用中:8080
- bartender - 从表单按钮更改命名数据源数据
- angular - 通过将数据发送到表单