3

Here is a simple example demonstrating the problem:

Consider the two bean classes Alpha and Beta:

public class Alpha {
    private String name;
    private Beta beta;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Beta getBeta() {
        return beta;
    }

    public void setBeta(Beta beta) {
        this.beta = beta;
    }
}


public class Beta {
    private Alpha alpha;

    public Alpha getAlpha() {
        return alpha;
    }

    public void setAlpha(Alpha alpha) {
        this.alpha = alpha;
    }
}

Then instances of Alpha and Beta are created, and the Alpha object is written to XML:

Alpha alpha = new Alpha();
Beta beta = new Beta();

alpha.setBeta(beta);
alpha.setName("Rama");
beta.setAlpha(alpha);

XMLEncoder encoder = new XMLEncoder(new BufferedOutputStream(new FileOutputStream("file.xml")));
encoder.writeObject(alpha);
encoder.close();

In java 6 this results in the following XML:

<?xml version="1.0" encoding="UTF-8"?>
<java version="1.6.0_24" class="java.beans.XMLDecoder">
 <object id="Alpha0" class="dk.kruger.Alpha">
  <void property="beta">
   <object class="dk.kruger.Beta">
    <void property="alpha">
     <object idref="Alpha0"/>
    </void>
   </object>
  </void>
  <void property="name">
   <string>Rama</string>
  </void>
 </object>
</java>

But in java 7 the result is:

<?xml version="1.0" encoding="UTF-8"?>
<java version="1.7.0_07" class="java.beans.XMLDecoder">
 <object class="dk.kruger.Alpha" id="Alpha0">
  <void property="beta">
   <object class="dk.kruger.Beta">
    <void property="alpha">
     <object idref="Alpha0">
      <void property="name">
       <string>Rama</string>
      </void>
     </object>
    </void>
   </object>
  </void>
 </object>
</java>

The XML generated by java 7 is much less human readable than the java 6 XML (especially, of course, for more complex examples). In the example above, the java 7 encoder defines the "name" property of "alpha" inside the definition of "beta", because "beta" also has a reference to "alpha". This behavior may result in deeply nested and ugly XML.

Is there a way to make the XML encoder in java 7 produce XML in java 6 style?

  • encoder.writeObject(alpha); alpha points to beta and beta points to alpha. There is a cyclic dependency there. – S.P. Oct 10 '12 at 20:57
  • Yeah, but don't think that is the problem. If you look carefully, you will see that the property "name" of Alpha is now hidden inside the reference to Alpha in Beta, instead of in alpha itself. Seems there is some kind of change to make all closing tags go to the bottom. And to the asker: Have you considered using something like XStream to create xml instead? – Tobb Oct 10 '12 at 21:13

0 Answers0