Scala XML Reader and Loop Elements
I read my colleague’s codes, he plan to parse the XML and convert that XML string into objects.
But the XML format can be different. So we need to loop all the elements and find the mapping and map the text value into our objects.
Here is how I loop all the label and text in XML.
package com.j2c.utils
/**
* Created by carl on 4/27/16.
*/
object XMLReader extends App{
println("reading XML--------------------")
val xml =
"""
|<book>
|<subject>fly in the air</subject>
|<author>Carl Luo</author>
|<price>1343</price>
|</book>
""".stripMargin
val node = scala.xml.XML.loadString(xml)
node.child.filter(!_.isAtom).foreach{ child =>
println("text=" + child.text)
println("label=" + child.label)
println("------------------------")
}
}
Here is the result:
com.intellij.rt.execution.application.AppMain com.j2c.utils.XMLReader
reading XML--------------------
text=fly in the air
label=subject
------------------------
text=Carl Luo
label=author
------------------------
text=1343
label=price
------------------------
Process finished with exit code 0
References:
http://stackoverflow.com/questions/31843334/xml-parse-and-return-list-of-objects
http://stackoverflow.com/questions/4748098/how-to-loop-over-a-list-of-children-found-inside-a-single-scala-xml-node
Scala XML Reader and Loop Elements
猜你喜欢
转载自sillycat.iteye.com/blog/2294413
今日推荐
周排行