4

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?

Ben Blank
  • 54,908
  • 28
  • 127
  • 156

2 Answers2

3

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);
Ian Dallas
  • 12,451
  • 19
  • 58
  • 82
  • suppose element 1 is like this and element 2 is like that your code will give us the right answer i am afraid it's not – confucius Sep 10 '11 at 22:44
  • @Nammari — Using the same `XMLOutputter` for both should ensure identical output for identical elements. I'm not sure how well namespaces will work, but I'll have to give this a try. – Ben Blank Sep 10 '11 at 23:34
  • @Nammari: Same thing Ben Blank said. The `Element` contains the data and does not describe the XML format. The XMLOutputter allows you to specify the format its outputted in so your question is moot provided the same XMLOutputter is used. – Ian Dallas Sep 11 '11 at 04:44
  • Okay, this isn't ideal with wonky namespaces (e.g. when working with two `Namespace` objects with identical URNs but different prefixes), but it's plenty good enough for my unit tests. If someone wants to get clever with namespaces later, on their head be it. :-) – Ben Blank Sep 11 '11 at 06:15
1

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!

Paul Grime
  • 14,970
  • 4
  • 36
  • 58
  • suppose element 1 is like this and element 2 is like that your code will give us the right answer i am afraid it's not – confucius Sep 10 '11 at 22:45
  • 1
    I think you've misunderstood. The output method is identical, so if the Elements are equal then the output will be too. Why do you think that the same XMLOutputter would close an Element with no children in different ways? – Paul Grime Sep 10 '11 at 22:53