Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
196 views
in Technique[技术] by (71.8m points)

Find XML nodes with wild card in name in Scala

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...