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. Sencha Touch 2 在MAC下详细的开发流程

    在不久的将来我相信Web App会流行的非常广, 能看到未来才能主宰未来.对于我们开发人员来说我觉得想成就一件伟大的事情,需要过硬的技术和好的想法,再加上决不放弃的精神,一定可以成功的. 以下在Mac ...

  2. Linear Regression(线性回归)(三)—代价函数J(θ)选择的概率解释

    (整理自AndrewNG的课件,转载请注明.整理者:华科小涛@http://www.cnblogs.com/hust-ghtao/) 在遇到线性回归问题时,我们总是令.可是我们为什么这样选择代价函数呢 ...

  3. WM_PAINT与WM_ERASEBKGND(用户操作和API这两种情况产生消息的顺序有所不同)

    1)当WM_PAINT不是由InvalidateRect产生时,即由最大化,最小化等产生时,或者移动产生(移动有时只会产生WM_ERASEBKGND消息)系统先发送WM_ERASEBKGND消息,再发 ...

  4. NYOJ 1066 CO-PRIME(数论)

    CO-PRIME 时间限制:1000 ms  |  内存限制:65535 KB 难度:3 描写叙述 This problem is so easy! Can you solve it? You are ...

  5. POJ 1273 Drainage Ditches(网络流,最大流)

    Description Every time it rains on Farmer John's fields, a pond forms over Bessie's favorite clover ...

  6. 【deep learning学习笔记】注释yusugomori的LR代码 --- 模型测试

    测试部分代码: void test_lr() { srand(0); double learning_rate = 0.1; double n_epochs = 500; int train_N = ...

  7. acFileStorage equivalent

    searching for a vcl that can enable embed any files within dfm similar to acfilestorage When there a ...

  8. 【ASP.NET Web API教程】4.1 ASP.NET Web API中的路由

    原文:[ASP.NET Web API教程]4.1 ASP.NET Web API中的路由 注:本文是[ASP.NET Web API系列教程]的一部分,如果您是第一次看本博客文章,请先看前面的内容. ...

  9. 默认情况下,不使用of子句表示在select所有的数据表中加锁(转)

    Select …forupdate语句是我们经常使用手工加锁语句.通常情况下,select语句是不会对数据加锁,妨碍影响其他的DML和DDL操作.同时,在多版本一致读机制的支持下,select语句也不 ...

  10. 【Demo 0005】Java基础-类继承性

    本章学习要点:       1.  了解Java继承特性;       2.  掌握继承实现方法;       3.  掌握override规则: 一.类继承特性       1.  继承定义:使用己 ...