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
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的方法。通过一个具体示例展示了如何读取XML字符串中的各个元素及其文本内容,并将其映射到对象中。此方法适用于不同格式的XML数据。
4572

被折叠的 条评论
为什么被折叠?



