javaxmljdomjdom-2

Remove whitespaces in end tags jdom


I am using JDom 2.0.5 to modify an xml. Also I have a Junit test case which check if it was correctly modified. It has an input xml, a method for testing (transformation xml) and a new xml (result). Later it compares output with a file which should be the final result.

FileUtils.contentEquals(newXml, modelXml);

But this is always false because every ending tag is modified by JDom automatically. I can't change the model because is a requirement that doesn't be modified.

Input: <properties/>
Output: <properties />    --> should be as input:: <properties/>

How can avoid that JDom changes this tags?

SAXBuilder builder = new SAXBuilder();
Document doc = (Document) builder.build(xmlFile);

// Add, remove some elements ...

XMLOutputter xmlOutput = new XMLOutputter();
xmlOutput.setFormat(Format.getPrettyFormat());
xmlOutput.output(doc, new FileWriter(newXml, false));

Solution

  • The "change" here is actually totally valid. The extra space makes no difference to the meaning of the XML.

    (Or to put it another way, the JDom data structure does not encode the presence or otherwise of non-significant whitespace in the source tags. Therefore, JDom cannot reproduce the input XML's white-space when it formats the output XML.)


    The real problem is that your expectation is incorrect. You simply can't reliably compare XML documents as if they were character sequences.

    Read this Q&A for various correct ways to compare XML in Java: