在 Scala 中查找名称中带有通配符的 XML 节点 [英] Find XML nodes with wild card in name in Scala
问题描述
我有以下 XML:
<data>
<a>...</a>
<b1>...</b1>
<c>...</c>
<b2>...</b2>
<d>...</d>
<b3>...</b2>
</data>
在 Scala 中,如何从 data
节点(即 Elem
对象)中提取以字符串b"开头的节点?在这种情况下,所需的值是三个节点的序列:
In Scala, how do I extract the nodes that start with the string "b" from the data
node (i.e., Elem
object)? In this case, the desired value is a sequence of three nodes:
[<b1>...</b1>, <b2>...</b2>, <b3>...</b3]
我已经试过了,但它不能编译:
I've tried this, but it doesn't compile:
val orderNodes: NodeSeq = /data/*[starts-with(name(), "b")]
推荐答案
小文档最简单的解决方案是用你需要的谓词过滤节点序列:
The simplest solution for small documents is to filter the sequence of nodes with the predicate you need:
val data = <data>
<a>...</a>
<b1>...</b1>
<c>...</c>
<b2>...</b2>
<d>...</d>
<b3>...</b3>
</data>
scala> (data \ "_").filter(_.label.startsWith("b"))
res1: scala.xml.NodeSeq = NodeSeq(<b1>...</b1>, <b2>...</b2>, <b3>...</b3>)
elem \ label
语法返回一个节点序列,其名称与 label
完全相同.而 elem \ "_"
是该语法的一个特例,它返回所有子元素.然后,您可以像处理任何普通的 Scala 集合一样处理该节点序列.
elem \ label
syntax returns a sequence of nodes, that have the name exactly equal to label
. And elem \ "_"
is a special case of that syntax, that returns all the child elements. Then you can work with that sequence of nodes like with any normal Scala collection.
这篇关于在 Scala 中查找名称中带有通配符的 XML 节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!