2016-12-16 78 views
0

我有这样的XML文本:遍历XML标记具有相同名称的

<apps> 
    <app><id>"abcde"</id></app> 
    <app><id>"xyz"</id></app> 
    <app><id>"bcn"</id></app> 
</apps> 

我使用的库scala.xml来处理它。

我想遍历app标签for循环是这样的:

(xmlText \\ "apps" \\ "app").foreach(app => { 
    //do something 
} 

然而,在这种情况下,我只能拿到第一app标签。

如何指定我想要第二个,第三个等?

回答

1

工作对我来说:

import scala.xml.Elem 
import scala.xml.XML 

object TagIter { 
    val xmlText = <apps> 
        <app><id>"abcde"</id></app> 
        <app><id>"xyz"</id></app> 
        <app><id>"bcn"</id></app> 
       </apps> 
    def main(args: Array[String]) { 
    (xmlText \\ "apps" \\ "app").foreach { app => 
     //do something 
     println(app.text) 
    } 
    } 
} 

"abcde" 
"xyz" 
"bcn" 

你的代码肯定遍历所有节点。如果您只想在第N个节点上执行操作,则可以添加一个变量,以跟踪迄今为止您已经看到的数量。

有这样太: https://stackoverflow.com/questions/4468461/select-nth-child-in-xquery-select-next-element

如果你申请一个索引表达式,你选择一个节点:

(xmlText \\ "apps" \\ "app")(1) 
"xyz" 
+0

谢谢。我的代码实际上有一个完全不同的问题。 – octavian