2016-12-16 77 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