Ben Blank
Ben Blank

Reputation: 56582

How can I compare two Elements for equivalency?

I'm writing unit tests for code which uses JDOM to read and write XML. I therefore need some way to compare the JDOM Element being produced by my code with a reference Element to ensure that they are equivalent (same name, namespace, and attributes, plus the same for its children, recursively).

Unfortunately, Element.equals only tests whether the elements are referentially equal. How can I best determine whether two elements represent identical trees?

Upvotes: 4

Views: 2459

Answers (2)

Ian Dallas
Ian Dallas

Reputation: 12741

The following should check to see if two XML element are equivalent:

String myElementString = XMLOutputter.outputString(myElement);
String testElementString = XMLOutputter.outputString(testElement);
boolean equals = myElementString.Equals(testElementString);

Upvotes: 3

Paul Grime
Paul Grime

Reputation: 15104

I can only think of three ways:

  1. Manually create code to compare using the publicly accessible fields of Element.
  2. Create code using Java reflection to enumerate the fields of Element and compare them all. Shallow or deep comparison is up to your needs.
  3. Use one of the xxxOutputter classes to output each Element and compare the output. E.g. create an XML string from each Element with org.jdom.output.XMLOutputter and compare the Strings.

All fairly yucky!

Upvotes: 1

Related Questions