views:

66

answers:

2

Hello, I am trying to flatten the xml output of xstream using a converter/marshaling with no luck. For example,

public class A{
    public B b;
    public int F;
    public String G; 
}

public class B{
    public String C;
    public String D;
    public int E;
}

is output as

<A>
  <B>
     <C></C>
     <D></D>
     <E></E>
  </B>
  <F></F>
  <G></G>
</A>

but I need

<A>
  <C></C>
  <D></D>
  <E></E>
  <F></F>
  <G></G>
</A>

is this possible? How to get rid of B? (C, D, E are uniquely named). Thanks. My attempt thus far has been

...    
public void marshal(Object value, HierarchicalStreamWriter writer,
    MarshallingContext context)
{
    B b = (B) value;
    writer.startNode("C");
    writer.setValue(b.getC());
    writer.endNode();

    writer.startNode("D");
    writer.setValue(b.getD());
    writer.endNode();

    writer.startNode("E");
    writer.setValue(b.getE());
    writer.endNode();
}
A: 

I found a temporary solution, though it is not the best.

If I set my canConvert function to check the surrounding object A instead of B, I can manipulate the entire inner object.

public boolean canConvert(Class c)
{
    return A.class == c;
}

Since I have to define all of class A, this is a lot more work (especially in a real XML object, instead of my contrived example). Does anyone know of a way to get the same result using a Converter on inner class B only?

public boolean canConvert(Class c)
{
    return B.class == c;
}
brian_d
A: 

Depending on how tied you are to XStream, you can do this quite easily in EclipseLink MOXy using the @XmlPath annotation:

public class A{ 
    @XmlPath(".") public B b; 
    public int F; 
    public String G;  
} 

public class B{ 
    public String C; 
    public String D; 
    public int E; 
} 

For Information on MOXy's XPath based mapping see:

Blaise Doughan
Thanks, but before switching the existing code to MOXy, I am hoping to find an equally nice solution in XStream (that I just don't know about)
brian_d
No problem, feel free to contact me when you get to the point when you want to port :).
Blaise Doughan
Blaise Doughan