Dmitry Korchemkin Dmitry Korchemkin - 1 year ago 91
Java Question

XStream delete unwanted fields of a collection

I have an object "Role" which can contain several "Privileges", which are objects too. Now, when i try to serialize Role with Xstream my xml looks like this:

<privileges class="org.hibernate.collection.PersistentSet">
<privilegeName>Admin Privilege</privilegeName>
<owner class="role" reference="../.."/>
<key class="int">3</key>
<storedSnapshot class="map">
<privilege reference="../../../set/privilege"/>
<privilege reference="../../../set/privilege"/>

I want it to look like this:

<privilegeName>Admin Privilege</privilegeName>

How can i omit/delete/not include all those additional fields? Seems like they are "utility" fields, added by hibernate, as i haven't declared them in my hbm.xml.
I already tried omitting them, adding Privileges collection as implicit and other things i found on XStream page.

I failed to create XSLT template as suggested below, but found that custom converter is really good and simple tool to do this job. Check the help page here -
And here's my marshal method:

public void marshal(Object value, HierarchicalStreamWriter writer,
MarshallingContext context) {
Role role = (Role) value;
for (Privilege privilege : role.getPrivileges()){

And xml it produces:

<roleName>Web Administrator</roleName>
<privilege>Web Access</privilege>

Answer Source

You can use XSL to transform your XML

XStream is delivered with a SAXSource implementation, that allows an XStream instance to be the source of a XML transformer.

Example Look at the following stylesheet:

<xsl:stylesheet version="1.0" xmlns:xsl="">
  <xsl:output method="xml" omit-xml-declaration="yes" indent="no"/>
  <xsl:template match="/cat">
      <xsl:apply-templates select="mName"/>

It is used here to remove the age of the cat on the fly (assuming XSLT is a string with the stylesheet above):

XStream xstream = new XStream();
xstream.alias("cat", Cat.class);

TraxSource traxSource = new TraxSource(new Cat(4, "Garfield"), xstream);
Writer buffer = new StringWriter();
Transformer transformer = TransformerFactory.newInstance().newTransformer(
    new StreamSource(new StringReader(XSLT)));
transformer.transform(traxSource, new StreamResult(buffer));

The result in the buffer:


Check this link for reference

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download