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. c# 使用OracleParameter,同时使用replace函数

    也算不上是手误吧,这个问题竟然困扰了我那么多天,就是更新代码的时候,使用replace,但是oracle在.net下竟然是不支持汉字,所谓使用类似update x set y='m' where y= ...

  2. android平台中,EventBus研究学习

             当一个Android应用功能越来越多的时候.app中各个部分之间通信.往往採用Observer的方式来进行,即注冊----通知----注销的方式运行 各类控件常常须要依据某个状态来更 ...

  3. Xamarin相关学习预估

    以前没有开发过app也没有了解过,当然只是用过,现在迫于形势无奈活到老学到老. 初步想了下app相关开发所涉及的知识点 一  app相关资源监视 1.1 网络监视器:https://github.co ...

  4. Delphi的String内存结构(够清楚) good

    变量s的内存结构为(字符串编码)A8 03 (字符宽度)01 00 (引用计数)FF FF FF FF (字符串长度)0A 00 00 00 (实际内容)31 32 33 34 35 36 37 38 ...

  5. jquery.form.js用法之清空form的方法

    本段代码摘取自jquery.form.js中,由于觉得该方法的使用性非常强,同时也可独立拿出来使用.该段代码言简意赅可以很好的作为学习参考. /** * Clears the form data. T ...

  6. OCA读书笔记(5) - 管理ASM实例

    Objectives:Describe the benefits of using ASMManage the ASM instanceCreate and drop ASM disk groupsE ...

  7. 修改注册表添加IE信任站点及启用Activex控件

    Windows Registry Editor Version 5.00 [HKEY_CURRENT_USER/Software/Microsoft/Windows/CurrentVersion/In ...

  8. windows系统port监听

    通常情况下.假设想发现全部已经使用的和正在监听的port,我们能够使用netstat命令. netstat并不是一个port扫描工具.假设你想扫描计算机开放了哪些port的话.建议使用本文介绍的方法. ...

  9. hdu1075What Are You Talking About (字典树)

    Problem Description Ignatius is so lucky that he met a Martian yesterday. But he didn't know the lan ...

  10. 与众不同 windows phone (28) - Feature(特性)之手机方向, 本地化, 应用程序的试用体验, 系统主题资源, 本地数据的加密解密

    原文:与众不同 windows phone (28) - Feature(特性)之手机方向, 本地化, 应用程序的试用体验, 系统主题资源, 本地数据的加密解密 [索引页][源码下载] 与众不同 wi ...