从Scala中的命令行获取Xpath [英] Get Xpath from command line in scala
问题描述
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测试\ fname \ p命令行上的 first,它会抛出
When i provide xpath test\"fname"\"first" on command line, it throws,
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的形式获取结果,
How to provide xpath as test\"fname"\"first" in command line and get result as,
<first>john</first>
推荐答案
您不能只是 cast String
到 NodeSeq
中。您可以尝试使用 XML.loadString(...)
解析。但这也不是您想要的,因为您的字符串不包含xml,它包含一些类似于xpath的选择。我不知道Scala的内置XML是否实际上支持Xpath。我只知道它在 NodeSeq
上有一些有趣的方法,例如 \
和 \ em
看起来有点像Xpath 。您可以做的是:
You cannot just cast a String
into a NodeSeq
. You could attempt to parse it with XML.loadString(...)
. But this is also not what you want, because your string does not contain xml, it contains some xpath-like selection. I don't know whether Scala's built-in XML actually supports Xpath. I only know that it has a few funny methods on NodeSeq
s like \
and \\
that look somewhat like Xpath. What you could do is:
- 从stdin中获取输入字符串
- 在
'\'
-字符 -
foldLeft
\
方法
- get input string from stdin
- split your input string at the
'\'
-character foldLeft
thetest
-xml node using the\
-method
类似的东西可以工作:
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
变量有什么关系?
Another note: you of course cannot use the String "test"
in your StdIn input. How is the compiler supposed to know that it has anything to do with the local test
-variable?
这篇关于从Scala中的命令行获取Xpath的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!