Ivan
Ivan

Reputation: 64227

How to evaluate an XML literal tag name in Scala?

How can I set an XML literal tag name by an expression? When it's just about a text inside a tag I use curly braces to enclose an expression to be evaluated like

<myTag>{My.expression}</mytag>

but I need something like

<{My.tag}>{My.expression}</{My.tag}>

Upvotes: 2

Views: 552

Answers (2)

4e6
4e6

Reputation: 10776

There is two ways:
1. Construct Elem
2. Use copy method on Elem object

scala> val tag = "my.tag"
tag: java.lang.String = my.tag

scala> val name = "my expression"
name: java.lang.String = my expression

scala> import xml._
import xml._

scala> Elem(null, tag, Null, TopScope, Text(name))
res0: scala.xml.Elem = <my.tag>my expression</my.tag>

scala> <foo/>
res1: scala.xml.Elem = <foo></foo>

scala> <foo/>.copy(label = tag, child = Text(name))
res2: scala.xml.Elem = <my.tag>my expression</my.tag>

Upvotes: 3

Peter Schmitz
Peter Schmitz

Reputation: 5844

I am not soo familiar with scala.xml but having a look at the API I can come up with this:

import scala.xml._
def TAG(tag: String) = new { 
  def apply(ns: Node*) = new {
    def ENDTAG = {
      val d = <D></D>
      new Elem(d.prefix,tag,d.attributes,d.scope,ns: _*)
    }
  }
}
val xml = <A>{TAG("B"){<C></C>}ENDTAG}</A>

println(xml) // <A><B><C></C></B></A>

Upvotes: 1

Related Questions