jelovirt
jelovirt

Reputation: 5892

How to access parent element in Scala XML

The scala.xml package represents XML with nodes of a labelled tree. But is this tree unidirectional in Scala 2.7, as there seems to be no way to access the Elem parent of a given Elem? The same seems to apply for parent Document. For example, in XOM you have getParent and getDocument accessors to navigate towards the root of the tree. Can this be done with Scala's XML API?

Upvotes: 14

Views: 3810

Answers (3)

Daniel C. Sobral
Daniel C. Sobral

Reputation: 297295

As mentioned by others, there are no parent links to make them efficient immutable structures. For example:

scala> val a = <parent><children>me</children></parent>
a: scala.xml.Elem = <parent><children>me</children></parent>

scala> val b = a.child(0)
b: scala.xml.Node = <children>me</children>

scala> val c = <newparent>{b}</newparent>
c: scala.xml.Elem = <newparent><children>me</children></newparent>

scala> a
res0: scala.xml.Elem = <parent><children>me</children></parent>

scala> b
res1: scala.xml.Node = <children>me</children>

scala> c
res3: scala.xml.Elem = <newparent><children>me</children></newparent>

No data structure was copied. The node pointed to by b is the very same node pointed to by both a and c. If it had to point to a parent, then you'd have to make a copy of it when you used it in c.

To navigate in that data structure the way you want, you need what is called a Purely Applicative XML Cursor.

Upvotes: 14

Ben James
Ben James

Reputation: 125327

It is unidirectional, so nodes are unaware of their parent.

You might be able to solve your problem by converting to a DOM. There doesn't seem to be anything in the standard library for this, but I found this thread on the subject which might be useful.

Upvotes: 1

jitter
jitter

Reputation: 54615

But is this tree unidirectional in Scala?

Yes. Due to the approach to immutability in scala.xml, nodes don't know their parent.

Upvotes: 3

Related Questions