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. sharepoint 2010 在自定义列表的字段上增加功能菜单

    sharepoint 2010 在自定义列表的字段上增加功能菜单方法 打开sharepoint designer 2010,找到需要修改的视图页面,例如allitem.aspx,编辑这个页面,点击高级 ...

  2. 获取字符宽度:并非自适应。coretext去计算

    获取字符宽度:并非自适应.coretext去计算 UniChar ch = [ns_str characterAtIndex:0]; CGGlyph glyph = 0; CTFontGetGlyph ...

  3. Net MVC微信扫码支付

    微信扫码支付+Asp.Net MVC 这里的扫码支付指的是PC网站上面使用微信支付,也就是官方的模式二,网站是Asp.net MVC,整理如下. 一.准备工作 使用的微信API中的统一下单方法,关键的 ...

  4. 【Cloud Foundry】Could Foundry学习(二)——核心组件分析

    在阅读的过程中有不论什么问题,欢迎一起交流 邮箱:1494713801@qq.com    QQ:1494713801 Cloud Foundry核心组件架构图例如以下: 主要组件:     Clou ...

  5. Prime Path (poj 3126 bfs)

    Language: Default Prime Path Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 11703   Ac ...

  6. 2006 ACM Northwestern European Programming Contest C题(二分求最大)

    My birthday is coming up and traditionally I'm serving pie. Not just one pie, no, I have a numberN o ...

  7. jsp中将后台传递过来的json格式的list数据绑定到下拉菜单select

    <span style="white-space:pre"> </span> <select><c:forEach var="f ...

  8. Git 使用规范流程(转)

    团队开发中,遵循一个合理.清晰的Git使用流程,是非常重要的. 否则,每个人都提交一堆杂乱无章的commit,项目很快就会变得难以协调和维护. 下面是ThoughtBot 的Git使用规范流程.我从中 ...

  9. 基础知识(3)- Java的基本程序设计结构

    3.1 一个简单的Java应用程序 3.2 注释 3.3 数据类型  3.3.1 整型  3.3.2 浮点类型  3.3.3 char类型  3.3.4 boolean类型 3.4 变量  3.4.1 ...

  10. Hongwei Xi

    Hongwei Xi Hongwei Xi Hongwei Xi's Curriculum Vita Hongwei Xi