Woking with XML
这一章主要介绍Scala对XML的支持,包括了如何使用XML字面量来创建节点,如何将XML保存到文件中以及如何从文件加载XML,如何利用模式匹配以及查询方法将XML分解
XML称为半结构化数据,是因为它比普通的字符串要有结构(将数据组装成树),但是它又比程序语言的对象更松散(XML允许在标签中存在自由格式的文本,并且缺少类型系统(实际上是有的))。半结构化的数据在于它在数据序列化和数据传输非常有帮助。
XML是由两种基本元素嵌套组成的:文本和标签。文本可以是任意顺序的字符,而标签则必须是一堆:起始标签和结束标签。除此之外,还有两项比较重要的属性: 1. 将斜杠加入到标签的标注后面,就可以给方便的表示一个空的元素,这时就不需要在写出一对标签了。 2. 起始标签可以包含属性,每一个属性都是以 name=value的性质存在,且值要用双引号或者单引号包起来
XML是Scala的内置类型,当然也存在字面量了。当你输入合法的XML时,编译器会将XML内容读入,组装成一个scala.xml.Elem类型的类
一些重要的XML类包括:
Class Node is the abstract superclass of all XML node classes.
Class Text is a node holding just text.
Class NodeSeq holds a sequence of nodes. (Also note that Node extends from NodeSeq)
在书写XML字面量时,可以通过 {} 作为转义字符,然后在 {} 中写Scala代码 (其实,这也是XML序列化的一种,你在花括号中写入代码,编译器会帮你将代码求值,然后转换成XML字面量 )
XML的序列化和反序列化是非常方便的,只要定义 toXML 和 fromXML 方法,就可以调用这两个方法进行序列化和反序列化了。
Scala支持类似xpath语法的格式来处理XML,所不同的是在xpath中要使用 / 和 // 来选择节点,而在Scala则使用 \ 和 \ (因为 // 在Scala表示注释,所以要选择反斜杠)。至于其他的语法则差不多,可以提取 text,提取子元素,提取属性
Scala还提供了一些方法用于将XML写入文件或者从文件中导入XML,如 save 和 loadFile
XML也支持模式匹配。 An XML pattern looks just like an XML literal. The main difference is that if you insert a { } escape, then the code inside the { } is not an expression but a pattern. A pattern embedded in { } can use the full Scala pattern language, including binding new variables, performing type tests, and ignoring content using the _ and _* patterns.
Modular Programming Using Objects
这一章主要讲如何做到利用Object做到模块化,不过因为没有怎么接触过大型项目,所以这部分看得也是模模糊糊
Scala也可以使用Spring提供的依赖反转机制,但是Scala也提供了自己的方法来实现系统级的模块化
另外,还有个有趣的内容: Any technique that aims to facilitate this system-level modularity needs to provide a few essentials. First, there should be a module construct that provides a good separation of interface and implementation. Second, there should be a way to replace one module with another that has the same interface without changing or recompiling the modules that depend on the replaced one. Lastly, there should be a way to wire modules together.
One of the ways Scala is a scalaable language is that the same constructs are used for constructs both small and large.
When making these modules more pluggable, however, it is important to avoid duplicating code.
If a module is an object, then a template for a module is a class. Just like a class describes the common parts of all its instances, a class can describe the parts of a module that are common to all of its possible configurations.
当模块太大时,可以把它分割成不同的特质,然后利用继承特质来组装模块
Scal提供了一个特别的 self type,Technically, a self type is an assumed type for this whenever this is mentioned within the class. Pragmatically, a self type specifies the requirements on any concrete class the trait is mixed into.