Scala: How to create XML literals

Problem: You want to create XML variables, and embed XML into your Scala code.

Solution

You can assign XML expressions directly to variables, as shown in these examples:

val hello = <p>Hello, world</p>
val p = <person><name>Edward</name><age>42</age></person>

In the REPL you can see that these variables are of type scala.xml.Elem:

scala> val hello = <p>Hello, world</p>
hello: scala.xml.Elem = <p>Hello, world</p>

scala> val p = <person><name>Edward</name><age>42</age></person>
p: scala.xml.Elem = <person><name>Edward</name><age>42</age></person>

As shown, you can embed XML directly into your Scala source code. There’s no need to embed the XML in double quotes to create a String; just assign an XML block to a variable.

Scala XML blocks can span multiple lines:

val foo = <p>Lorem ipsum 
          dolor sit amet, 
          consectetur adipisicing elit
          et cetera, et cetera</p>

A block can take as many lines as needed to solve the current problem. As shown in the following code, an XML literal can also be the result of a method or function:

def getXml =
  <pizza>
    <crust type="thin" size="14" />
    <topping>cheese</topping>
    <topping>sausage</topping>
  </pizza>

More often you’ll return dynamically generated XML from a method. I’ll demonstrate this in a future recipe.

Discussion

If you’re given a block of XML as a String, you can convert it into an XML literal with the loadString method of the scala.xml.XML object:

scala> val dog = <?pdf-cr?>
xml.XML.loadString("<dog><name>Rocky</name><age>12</age></dog>")
dog: scala.xml.Elem = <dog><name>Rocky</name><age>12</age></dog>

This results in an Elem object, as in the previous examples.

Note that a poorly formed XML string will lead to a SAXParseException:

scala> val x = scala.xml.XML.loadString("")
org.xml.sax.SAXParseException: Premature end of file.

scala> val x = scala.xml.XML.loadString("a")
org.xml.sax.SAXParseException: Content is not allowed in prolog.

scala>val x = scala.xml.XML.loadString("<a>")
org.xml.sax.SAXParseException: XML document structures must start and end within the same entity.

The following figure shows the main classes in the scala.xml class hierarchy:

image

The Scaladoc states that the Elem class “extends the Node class, providing an immutable data object representing an XML element.” An Elem has a label, attributes, and children, as you’ll see in many examples in this chapter.

When parsing XML, the classes you’ll run into most often are Elem, Node, and NodeSeq. These classes are described here:

Name Description


Elem An immutable object that represents an XML element.

Node An abstract class representing nodes in an XML tree.
It contains an implementation of XPath methods like \ and \.

NodeSeq A wrapper around Seq[Node], with XPath and comprehension methods.
Typically seen as the result of XPath searches.

Although the Elem class has more than 160 methods, don’t be intimidated; many of these come from the ability to treat an Elem as a sequential collection. There are a small handful of commonly used, XML-specific methods.

The NodeSeq class is simpler. Like the Elem class, it implements the \ and \\methods for XPath searching, and then is primarily composed of common collection methods.

If you get deeply involved in XML parsing and creation, you’ll also run into some of the other Scala classes. The most common of those are listed here:

Name Description


NodeBuffer Extends ArrayBuffer[Node], and adds an &+ method that lets you build
a sequence of XML nodes using a fluent style.

PCData From the Scaladoc, “this class (which is not used by all XML parsers, but
always used by the XHTML one) represents parseable character data, which
appeared as CDATA sections in the input and is to be preserved as CDATA sections
in the output.” Example:

                scala> val x = PCData("<p>hello</p>")
                x: scala.xml.PCData = <![CDATA[<p>hello</p>]]>

Text Implements an XML node for text (PCDATA). Programming in Scala refers to it as,
“A node holding just text.” Example:

                scala> **val x = Text("<p>Sundance</p>")**
                x: scala.xml.Text = <p>Sundance</p>

Unparsed An XML node for unparsed content. Per the Scaladoc, it will output verbatim, and
“all bets are off regarding wellformedness etc.” Example:

                // intentional error
                scala> val x = Unparsed("</p>foo<p>")
                x: scala.xml.Unparsed = </p>foo<p>

See Also

See the following links for more information:

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市须板,隨后出現(xiàn)的幾起案子窿凤,更是在濱河造成了極大的恐慌,老刑警劉巖食磕,帶你破解...
    沈念sama閱讀 222,464評論 6 517
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡粤咪,警方通過查閱死者的電腦和手機鲤遥,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,033評論 3 399
  • 文/潘曉璐 我一進店門沐寺,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人盖奈,你說我怎么就攤上這事混坞。” “怎么了钢坦?”我有些...
    開封第一講書人閱讀 169,078評論 0 362
  • 文/不壞的土叔 我叫張陵究孕,是天一觀的道長。 經(jīng)常有香客問我爹凹,道長厨诸,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 59,979評論 1 299
  • 正文 為了忘掉前任禾酱,我火速辦了婚禮微酬,結(jié)果婚禮上绘趋,老公的妹妹穿的比我還像新娘。我一直安慰自己颗管,他們只是感情好陷遮,可當我...
    茶點故事閱讀 69,001評論 6 398
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著垦江,像睡著了一般帽馋。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上比吭,一...
    開封第一講書人閱讀 52,584評論 1 312
  • 那天绽族,我揣著相機與錄音,去河邊找鬼梗逮。 笑死项秉,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的慷彤。 我是一名探鬼主播娄蔼,決...
    沈念sama閱讀 41,085評論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼底哗!你這毒婦竟也來了岁诉?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 40,023評論 0 277
  • 序言:老撾萬榮一對情侶失蹤跋选,失蹤者是張志新(化名)和其女友劉穎涕癣,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體前标,經(jīng)...
    沈念sama閱讀 46,555評論 1 319
  • 正文 獨居荒郊野嶺守林人離奇死亡坠韩,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,626評論 3 342
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了炼列。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片只搁。...
    茶點故事閱讀 40,769評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖俭尖,靈堂內(nèi)的尸體忽然破棺而出氢惋,到底是詐尸還是另有隱情,我是刑警寧澤稽犁,帶...
    沈念sama閱讀 36,439評論 5 351
  • 正文 年R本政府宣布焰望,位于F島的核電站,受9級特大地震影響已亥,放射性物質(zhì)發(fā)生泄漏熊赖。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 42,115評論 3 335
  • 文/蒙蒙 一虑椎、第九天 我趴在偏房一處隱蔽的房頂上張望震鹉。 院中可真熱鬧的妖,春花似錦、人聲如沸足陨。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,601評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽墨缘。三九已至,卻和暖如春零抬,著一層夾襖步出監(jiān)牢的瞬間镊讼,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,702評論 1 274
  • 我被黑心中介騙來泰國打工平夜, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留蝶棋,地道東北人。 一個月前我還...
    沈念sama閱讀 49,191評論 3 378
  • 正文 我出身青樓忽妒,卻偏偏與公主長得像玩裙,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子段直,可洞房花燭夜當晚...
    茶點故事閱讀 45,781評論 2 361

推薦閱讀更多精彩內(nèi)容