Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala XML API: Why allow NodeSeq as attribute values?

Tags:

xml

scala

It seems attribute values are of type Seq[Node].

scala> <a b="1"/>.attribute("b")             
res11: Option[Seq[scala.xml.Node]] = Some(1)

This means you can assign XML as an attribute value.

scala> <a b={<z><x/></z>}/>.attribute("b")            
res16: Option[Seq[scala.xml.Node]] = Some(<z><x></x></z>)

scala> <a b={<z><x/></z>}/>.attribute("b").map(_ \ "x")
res17: Option[scala.xml.NodeSeq] = Some(<x></x>)

scala> new xml.PrettyPrinter(120, 2).format(<a b={<z><x/></z>}/>)
res19: String = <a b="<z><x></x></z>"></a>

This seems funky to me. I've never seen XML as attribute values in the real world. Why is it allowed? Why is an attribute value simply not of type String?

like image 632
Synesso Avatar asked Jan 07 '11 03:01

Synesso


1 Answers

From the scala.xml "draft" book by Burak Emir:

begin quote

At first sight, it appears that attributes should only be strings and nothing else. However, there are two reasons to allow the same kind of nodes (other than element nodes) that can appear within XML: data values and entity references.

<foo name= "s&uuml;ss" life={Atom(42)}>

end quote

Now I've tried that in 2.8.0 and it doesn't quite compile - I need to use new Atom(42). But I can type something like this:

<foo name={List(Text("s"), EntityRef("uuml"), Text("ss"))}/> 

So that was part of the rationale for leveraging nodes for attributes. And yeah it's a bit funky.

like image 171
huynhjl Avatar answered Nov 03 '22 00:11

huynhjl