Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XML equality problem with Scala

Tags:

xml

scala

I've stumbled upon a peculiarity of XML equality in Scala:

scala> val x = <a>12</a>
x: scala.xml.Elem = <a>12</a>

scala> val y = <a>{1}2</a>
y: scala.xml.Elem = <a>12</a>

scala> x == y
res0: Boolean = false

What I think is happening is that two xml.Text objects are being created, and that is different than one. However, this isn't how it works in the XML spec :) and I wonder if there is any way to compare equality so that this would return true.

Thanks!

like image 522
Aaron Yodaiken Avatar asked Mar 29 '11 03:03

Aaron Yodaiken


1 Answers

The <a>12</a> represents an element with a single child node with the value "12", whereas <a>{1}2</a> represents an element with two child nodes, with values "1" and "2", respectively.

They are logically distinguishable in Scala: x.child is ArrayBuffer(12) whereas y.child is ArrayBuffer(1, 2), and therefore they are inequal.

What about the XML spec? By my reading, those two XML objects are not equal. According to the XML spec, an element's contents consists of a sequence of one or more things (which DOM calls "nodes"), and those things can be CharData. Therefore, it is logical for an element to have two adjacent CharData children, and this is considered logically different from a single concatenated CharData child.

If you really want to consider them equal, you should write a normalisation pass that takes an XML object and concatenates any adjacent text nodes, and then perform an equality test.

like image 152
mgiuca Avatar answered Oct 06 '22 00:10

mgiuca