8. 
XML

8.1. 
   生成

Scala原生支持xml,就如同Java支持String一样,这就让生成xml和xhtml非常easy优雅:

val name = "james"

val age = 10

val html = <html>name={name}, age="{age}"</html> toString

// <html>name=james, age=&quot;10&quot;</html>

又如:

val html = <html><head><title>{myTitle}</title></head><body>{"hello world"}</body></html>

更复杂的样例:

val x = <r>{(1 to 5).map(i => <e>{i}</e>)}</r>

// <r><e>1</e><e>2</e><e>3</e><e>4</e><e>5</e></r>

val x0 = <users><user name="qh"/></users>

val <users>{u}</users> = x0  // u: scala.xml.Node = <user name="qh"></user>

By the way, if you want to include a curly brace (`{' or `}') as XML text, as opposed to using them to escape to Scala code, simply write two curly braces in
a row:

  scala> <a> {{{{brace yourself!}}}} </a>
res1: scala.xml.Elem = <a> {{brace yourself!}} </a>

8.2. 
     xml文件

xml.XML loadString "<p></p>"

xml.XML loadFile "abc.xml"

xml.XML.saveFull("foo.xml", node, "UTF-8", xmlDecl: Boolean, doctype : DocType)

8.3. 
    读取:

val x = <r>{(1 to 5).map(i => <e>{i}</e>)}</r>

// <r><e>1</e><e>2</e><e>3</e><e>4</e><e>5</e></r>

(x \ "e") map (_.text.toInt) // List(1, 2, 3, 4, 5)

val x0 = <users>

<user name="qh"><age>20</age></user>

<user name="james"><age>30</age></user>

</users>

(x0 \ "user") // <user name="qh"><age>20</age></user>, <user name="james"><age>30</age></user>)

(x0 \ "user" \ "age") // (<age>20</age>, <age>30</age>)

(x0 \ "age")  // 直接下级: ()

(x0 \\ "age") // 全部下级:(<age>20</age>, <age>30</age>)

(x0 \ "_") 全部

8.4 
     訪问属性

val x = <uu><u name="qh" /><u name="james" /><u name="qiu" /></uu>

scala> (x \ "u" \\ "@name") foreach println

qh

james

qiu

样例:

val data =

<shopping>

  <item name="bread" quantity="3" price="2.50"/>

  <item name="milk" quantity="2" price="3.50"/>

< /shopping>



val res = for (item <- data \ "item" ; 

                 price = (item \ "@price").text.toDouble ; 

                 qty = (item \ "@quantity").text.toInt)

           yield (price * qty)



printf("$%.2f\n", res.sum)

8.5 
     Deserialization

You can write of a serializer, a parser from XML back into your internal data structures. For example, you can parse back a CCTherm instance by using the following code:

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

}

This code searches through an input XML node, named node, to find each of the six pieces of data needed to specify a CCTherm. The data that is text is extracted with .text and left as is.

8.6 
   格式化输出

val pp = new xml.PrettyPrinter(80, 4)  // 行宽 80,缩进为 4

pp formatNodes <b><a/></b>

结果是字符串

<b>

<a></a>

</b>

8.7 
   Pattern
matching on XML

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. Here is a simple example:

def proc(node: scala.xml.Node): String =

node match {

case <a>{contents}</a> => "It's an a: "+ contents

case <b>{contents}</b> => "It's a b: "+ contents

case _ => "It's something else."

}

scala> proc(<a>apple</a>)

res16: String = It's an a: apple

scala> proc(<b>banana</b>)

res17: String = It's a b: banana

scala> proc(<c>cherry</c>)

res18: String = It's something else.

val catalog =

<catalog>

  <cctherm>

    <description>hot dog #5</description>

    <yearMade>1952</yearMade>

    <dateObtained>March 14, 2006</dateObtained>

    <bookPrice>2199</bookPrice>

    <purchasePrice>500</purchasePrice>

    <condition>9</condition>

  </cctherm>

  <cctherm>

    <description>Sprite Boy</description>

    <yearMade>1964</yearMade>

    <dateObtained>April 28, 2003</dateObtained>

    <bookPrice>1695</bookPrice>

    <purchasePrice>595</purchasePrice>

    <condition>5</condition>

  </cctherm>

</catalog>

catalog match {

  case <catalog>{therms @ _*}</catalog> =>

    for (therm @ <cctherm>{_*}</cctherm> <therms)

      println("processing: "+(therm \ "description").text)

}

processing: hot dog #5

processing: Sprite Boy

Scala的XML操作的更多相关文章

  1. 初试Scala解析XML

    使用Scala解析XML,充分体现了函数式编程的特点,简洁和明了.用Java去解析不是不行,只不过代码不够清晰明了. 首先先把XML文件读入到内存里: val someXml = XML.loadFi ...

  2. Scala入门到精通——第二十七节 Scala操纵XML

    本节主要内容 XML 字面量 XML内容提取 XML对象序列化及反序列化 XML文件读取与保存 XML模式匹配 1. XML 字面量 XML是一种很重要的半结构化数据表示方式,眼下大量的应用依赖于XM ...

  3. LINQ系列:LINQ to XML操作

    LINQ to XML操作XML文件的方法,如创建XML文件.添加新的元素到XML文件中.修改XML文件中的元素.删除XML文件中的元素等. 1. 创建XML文件 string xmlFilePath ...

  4. T-Sql(五)xml操作

    t-sql中的xml操作在我们平时做项目的过程中用的很少,因为我们处理的数据量很少,除非一些用到xml的地方,t-sql中xml操作一般用在数据量很大,性能优化的地方,当然我在平时做项目的时候也是没用 ...

  5. XML格式示例 与 XML操作(读取)类封装

    header('Content-Type: text/xml'); <?xml version="1.0" encoding="utf-8" standa ...

  6. 【Java EE 学习 33 上】【JQuery样式操作】【JQuery中的Ajax操作】【JQuery中的XML操作】

    一.JQuery中样式的操作 1.给id=mover的div采用属性增加样式.one $("#b1").click(function(){ $("#mover" ...

  7. 简单的XML操作类

    /// <summary> /// XmlHelper 的摘要说明. /// xml操作类 /// </summary> public class XmlHelper { pr ...

  8. .net学习笔记---xml操作及读写

    一.XML文件操作中与.Net中对应的类 微软的.NET框架在System.xml命名空间提供了一系列的类用于Dom的实现. 以下给出XML文档的组成部分对应.NET中的类: XML文档组成部分 对应 ...

  9. C#常用操作类库三(XML操作类)

    /// <summary> /// XmlHelper 的摘要说明. /// xml操作类 /// </summary> public class XmlHelper { pr ...

随机推荐

  1. python 站点爬虫 下载在线盗墓笔记小说到本地的脚本

    近期闲着没事想看小说,找到一个全是南派三叔的小说的站点,决定都下载下来看看,于是动手,在非常多QQ群里高手的帮助下(本人正則表達式非常烂.程序复杂的正则都是一些高手指导的),花了三四天写了一个脚本 须 ...

  2. Beauty of Array

    Description Edward has an array A with N integers. He defines the beauty of an array as the summatio ...

  3. 构建基于Jenkins + Github的持续集成环境

    搭建持续集成首先要了解什么是持续集成,带着明确的目标去搭建持续集成环境才能让我们少走很多弯路.持续集成(Continuous integration)简称CI,是一种软件开发的实践,可以让团队在持续集 ...

  4. 基于visual Studio2013解决面试题之0407数组差

     题目

  5. Redis C客户端API - God's blog - 博客频道 - CSDN.NET

    Redis C客户端API - God's blog - 博客频道 - CSDN.NET Redis安装步骤: 1.redis server安装 wget http://redis.googlecod ...

  6. JavaScript移除数组元素

    //数组移除长度方法 var array=[]; array[0]="张三"; array[1]="李四"; array[2]="王五"; ...

  7. Swift中使用typealias定义一个闭包closure

    在OC中我们定义一个Blocks是这样定义的: typedef void (^ZWProgressHUDCompletionBlock)(); 在Swift中定义一个闭包是这种: typealias ...

  8. 查找MobileSafari WebKit revision number的方法

    Mobile Safari是开源的Mac Safari的iOS版本,然而iOS WebKit并不完全开源,只公开了部分的WebCore和JavaScriptCore.有时需要知道iOS Safari的 ...

  9. 漫谈并发编程(六):java中一些经常使用的并发构件的介绍

    CountDownLatch      它被用来同步一个或多个任务,强制它们等待其他任务运行的一组操作完毕.      你能够向CountDownLatch对象设置一个初始计数值,不论什么在这个对象上 ...

  10. [JS练习] 瀑布流照片墙

    记录JS实现瀑布流照片墙效果 首先是前端页面 <!DOCTYPE html> <html lang="en"> <head> <meta ...