拆解xml
- 抽取文本
主要利用xpath的函数 text,如
val valxml = <a> sounds <tag/> good</a>
//1. 抽取文本
val extractText = valxml.text
println("extractText=" + extractText)
extractText= sounds good
- 抽取子元素
只要调用 \ 元素名
//2. 抽取子元素
val subXml= <a><b><c>hello</c></b></a>
println(subXml \ "b")
hello
* 注意*
如果要深度搜索的话,将用双斜杠( \) 代替 单斜杠()
- 属性抽取
只需要在属性名前用@符号
//属性抽取,只需要在属性名前用@符号
val attXml = <employee name="Joe" rank="code monkey" serial="123" >
<work type="早班">
<price>10</price>
<from>8</from>
<to>16</to>
</work>
<work type="中班">
<price>9</price>
<from>16</from>
<to>24</to>
</work>
<work type="晚班">
<price>1</price>
<from>0</from>
<to>8</to>
</work>
</employee>
println(attXml \\ "@name")
Joe
xml 系列化
/**
* xml 序列化
*/
abstract class CCTherm {
val description: String
val yearMade: Int
val dateObtained: String
val bookPrice: Int
val purchasePrice: Int
val condition: Int
override def toString = description
def toXML =
<cctherm>
<description>{description}</description>
<yearMade>{yearMade}</yearMade>
<dateObtained>{dateObtained}</dateObtained>
<bookPrice>{bookPrice}</bookPrice>
<purchasePrice>{purchasePrice}</purchasePrice>
<condition>{condition}</condition>
</cctherm>
}
xml 反系列化
def fromXml(node:scala.xml.Node):CCTherm=
new CCTherm {
val description = (node\ "description").text
val yearMade = (node\ "yearMade").text.toInt
val dateObtained = (node\ "dateObtained").text
val bookPrice = (node\ "bookPrice").text.toInt
val purchasePrice = (node\ "purchasePrice").text.toInt
val condition = (node\ "condition").text.toInt
}
xml 加载和保存
- xml加载
调用scala.xml.XML.save方法,参数有
文件名
要保存的节点
是否包含xml声明
文档类型
scala.xml.XML.save("therm1.xml", node, "utf-8", true, null);
- xml 保存
调用scala.xml.XML.loadFile 方法,例如:
scala.xml.XML.loadFile ("therm1.xml")