Scala XML Reader and Loop Elements

本文介绍了一种使用Scala解析并遍历XML的方法。通过一个具体示例展示了如何读取XML字符串中的各个元素及其文本内容,并将其映射到对象中。此方法适用于不同格式的XML数据。
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
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值