【问题标题】:Get Xpath from command line in scala从scala中的命令行获取Xpath
【发布时间】:2018-03-09 10:32:21
【问题描述】:
import scala.io.Source
import scala.xml.{Node, NodeSeq, XML}

object scalaTest extends App {


var test= <name>person
<fname>doe
<first>john</first>
</fname>
</name>


var s=scala.io.StdIn.readLine
var result=s.asInstanceOf[NodeSeq]

println(result)


}

当我在命令行上提供 xpath test\"fname"\"first" 时,它会抛出,

test\"fname"\"first"
Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to scala.xml.NodeSeq
    at scalaTest$.delayedEndpoint$scalaTest$1(scalaTest.scala:15)
    at scalaTest$delayedInit$body.apply(scalaTest.scala:4)
    at scala.Function0.apply$mcV$sp(Function0.scala:34)
    at scala.Function0.apply$mcV$sp$(Function0.scala:34)
    at scala.runtime.AbstractFunction0.apply$mcV$sp(AbstractFunction0.scala:12)
    at scala.App.$anonfun$main$1$adapted(App.scala:76)
    at scala.collection.immutable.List.foreach(List.scala:389)
    at scala.App.main(App.scala:76)
    at scala.App.main$(App.scala:74)
    at scalaTest$.main(scalaTest.scala:4)
    at scalaTest.main(scalaTest.scala)

如何在命令行中提供 xpath 作为 test\"fname"\"first" 并得到结果,

<first>john</first>

【问题讨论】:

  • 我没有在 Scala 中使用 XML 的经验,但不应该与在您的代码中进行测试相关吗?或者这些有什么关系?

标签: xml scala xpath command-line


【解决方案1】:

您不能只是将String转换NodeSeq。您可以尝试使用XML.loadString(...) 解析它。但这也不是您想要的,因为您的字符串不包含 xml,它包含一些类似 xpath 的选择。我不知道 Scala 的内置 XML 是否真的支持 Xpath。我只知道它在NodeSeqs 上有一些有趣的方法,例如\\\看起来有点像 Xpath。你可以做的是:

  • 从标准输入获取输入字符串
  • '\'-字符处分割您的输入字符串
  • foldLefttest-xml 节点使用\-方法

这样的工作:

import scala.xml.NodeSeq
val test = <name>person<fname>doe<first>john</first></fname></name>
val xpath = """fname\first""" // or read from StdIn
val selectedElement = xpath.split("\\\\").foldLeft[NodeSeq](test){
  case (elem, tagName) => elem \ tagName 
}

// gives result:
// res20: scala.xml.NodeSeq = NodeSeq(<first>john</first>)

或更短:

val selectedElement = xpath.split("\\\\").foldLeft[NodeSeq](test)(_ \ _)

另一个注意事项:您当然不能在 StdIn 输入中使用字符串 "test"。编译器应该如何知道它与本地的test-变量有什么关系?

【讨论】:

  • 这很好用!但是当我需要给 XPATH 一些类似的东西时(test\"fname"\"first")(0),我不认为原生 scala XML 不支持这个!
  • @s.Doe 我认为 Scala 对 XML 的原生支持在 2010 年比现在更受欢迎。例如here, Prof. Odersky himself says that "XML literals {...} stick{s} out like a sore thumb"。我不太了解 scala 的 XML 支持,但也许使用一个单独的库会更容易,它更重视 XPath。
  • 非常感谢@Andrey
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-22
  • 1970-01-01
  • 1970-01-01
  • 2012-04-10
  • 2014-01-03
相关资源
最近更新 更多