8

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?

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.