Scala的XML操作



8. 
XML

8.1. 
   生成

Scala原生支持xml,就如同Java支持String一样,这就让生成xml和xhtml很简单优雅:

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

时间: 2024-10-30 02:56:18

Scala的XML操作的相关文章

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

本节主要内容 XML 字面量 XML内容提取 XML对象序列化及反序列化 XML文件读取与保存 XML模式匹配 1. XML 字面量 XML是一种非常重要的半结构化数据表示方式,目前大量的应用依赖于XML,这些应用或利用XML作为数据交换格式,或利用XML进行文件配置等.像JAVA.C++及其它流行的程序开发语言都是依赖于第三方库来实现XML的操作,例如JAVA经常通过JDOM,DOM4J等XML处理工具进行XML的操纵,但Scala提供了对XML的原生支持,通过scala.xml._包下的类或

Scala解析XML

使用Scala解析XML. 首先先把XML文件读入到内存里: val someXml = XML.loadFile("file/Example.xml") 这样someXml是一个scala.xml.Elem对象. Scala XML API提供了类似XPath的语法来解析XML.在NodeSeq这类父类里,定义了两个很重要的操作符("\"和"\\"),用来获得解析XML: \ :Projection function, which return

XML操作

XML: XML 指可扩展标记语言 XML 被设计用来传输和存储数据. XML 被设计用来结构化.存储以及传输信息. xml文档展示: -----------------------------xml文档 <?xml version="1.0" encoding="ISO-8859-1"?> <note> <to>George</to> <from>John</from> <heading

c#xml操作

简单的xml操作--解析技能xml xml文件 <skills> <skill> <id>1</id> <name lang="cn">大荒囚天指</name> <demage>100</demage> </skill> <skill> <id>2</id> <name lang="en">绝对零度</na

使用 IntraWeb (31) - IntraWeb 的 Xml 操作使用的是 NativeXml

在 IWNativeXml 单元. 知道了这个, 以后在其他 Delphi 程序中也可以直接 Uses IWNativeXml 了. TNativeXml (IWNativeXml.TNativeXml property AbortParsing: Boolean property BinaryEncoding: TBinaryEncodingType property CommentString: UTF8String property DropCommentsOnParse: Boolean

C#对一个XML操作的实用类

using System; using System.Collections.Generic; using System.Text; using System.Xml; using System.Data; using System.IO; namespace eBlog.Common.Files { public class XmlHelper { protected string strXmlFile; protected XmlDocument objXmlDoc = new XmlDoc

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

/// <summary> /// XmlHelper 的摘要说明. /// xml操作类 /// </summary> public class XmlHelper { protected string strXmlFile; protected XmlDocument objXmlDoc = new XmlDocument(); public XmlHelper(string XmlFile) { // // TODO: 在这里加入建构函式的程序代码 // try { objX

php xml 操作。

参考 文章:http://www.cnblogs.com/zcy_soft/archive/2011/01/26/1945482.html DOMDocument相关的内容. 属性: Attributes 存储节点的属性列表(只读) childNodes 存储节点的子节点列表(只读) dataType 返回此节点的数据类型 Definition 以DTD或XML模式给出的节点的定义(只读) Doctype 指定文档类型节点(只读) documentElement 返回文档的根元素(可读写) fi

C#:XML操作类

写的一个XML操作类,包括读取/插入/修改/删除. using System;using System.Data;using System.Configuration;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Web.UI.HtmlContro