Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have the following XML:

<data>
    <a>...</a>
    <b1>...</b1>
    <c>...</c>
    <b2>...</b2>
    <d>...</d>
    <b3>...</b2>
</data>

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")]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
195 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...