Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access parent element in Scala XML

Tags:

xml

scala

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?

like image 685
jelovirt Avatar asked Oct 17 '09 13:10

jelovirt


1 Answers

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.

like image 102
Daniel C. Sobral Avatar answered Oct 16 '22 21:10

Daniel C. Sobral