將XML中的account_number、model數據提取出來,並以account_number:model格式存儲
node
一、XML文件數據格式json
<activations>
<activation timestamp="1225499258" type="phone">
<account-number>316</account-number>
<device-id> d61b6971-33e1-42f0-bb15-aa2ae3cd8680 </device-id>
<phone-number>5108307062</phone-number>
<model>iFruit 1</model>
</activation> … </activations>
二、存儲格式:函數
1234:iFruit 1
987:Sorrento F00L
4566:iFruit 1 oop
import scala.xml._ //給定一個包含XML的字符串,解析字符串,並返回字符串中包含的激活XML記錄(節點)的迭代器
def getactivations(xmlstring: String): Iterator[Node] = { val nodes = XML.loadString(xmlstring) \\ "activation" nodes.toIterator } // 給定一個激活記錄(XML節點),返回模型名稱
def getmodel(activation: Node): String = { (activation \ "model").text } // 給定一個激活記錄(XML節點),返回賬號
def getaccount(activation: Node): String = { (activation \ "account-number").text } //mydata1:(0:"路徑":1:"內容") //wholeTextFiles 建立包含文件名、文件內容的RDD
var mydata1 = sc.wholeTextFiles("file:/home/training/training_materials/data/activations/") //flatmap 遍歷RDD中的文件內容獲得文件內容的RDD
val mydata2=mydata1.flatMap(line => getactivations(line._2)) //經過函數獲取對應節點的值,建立account-number:model RDD
val mydata3=mydata2.map(line => getaccount(line)+":"+getmodel(line)) //輸出數據,測試數據格式
mydata3.take(10).foreach(println)
sc.wholeTextFiles (directory) 測試
從HDFS中讀取文本文件的目錄,本地文件系統(在全部節點上可用),或者任何hadoop支持的文件系統URI。每一個文件被讀取爲單個記錄,而後返回到鍵值對中,其中鍵是每一個文件的路徑,值是每一個文件的內容。ui
例如:spa
(filel.json,{"firstName":"Fred","lastName":"Flintstone","userid":"123"} )
(file2.json,{"firstName":"Barney","lastName":"Rubble","userid":"234"} )
(file3.json,... )
(file4.json,... )
scala