XSD验证:发生异常时如何获取当前节点名称

时间:2018-10-31 07:56:48

标签: xml scala xsd xsd-validation

我正在执行xsd验证,并尝试在发生异常时获取当前节点名称,但是我正在获取 public void saveData(View view) { User user = new User(1, "Rajneesh", "hi this is rajneesh shukla"); userList.add(user); SharedPreferences preferences = getSharedPreferences("DATA" , MODE_PRIVATE); SharedPreferences.Editor editor = preferences.edit(); Gson gson = new Gson(); String s = gson.toJson(userList); editor.putString("USER_DATA", s); editor.apply(); } public void logData(View view) { SharedPreferences preferences = getSharedPreferences("DATA", MODE_PRIVATE); String s = preferences.getString("USER_DATA", "Data is not saved" ); Gson gson = new Gson(); Type type = new TypeToken<ArrayList<User>>(){} .getType(); ArrayList<User> mUser = gson.fromJson(s, type); }

我尝试了下面的代码-

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
 }
}

请帮助我完成它。谢谢!

1 个答案:

答案 0 :(得分:0)

这是一个有趣的想法,但是当验证失败时,无法从scala.xml.Elem获取javax.xml.validation.Validator,因为javax对{{1}一无所知}。如果只用scala.xml来召唤它会很好,但是需要在运行时更改类型asInstanceOf[Elem]的类。