If I understand correctly, you want to check in CConverter
whether B
node already exists in hierarchy. If the structure is as above that's always is true
. Marshalling process starts from the root object and goes into internal properties. So, to write C
node first B
must exist.
Assume you have simple POJO
structure like below:
class A {
public B b = new B();
}
class B {
public C c = new C();
}
class C {
}
Now, we can implement converter for A
and B
:
class AConverter implements Converter {
public boolean canConvert(Class clazz) {
return clazz.equals(A.class);
}
public void marshal(Object value, HierarchicalStreamWriter writer, MarshallingContext context) {
System.out.println("Marshalling A!");
A a = (A) value;
if (a.b != null) {
writer.startNode("B");
context.convertAnother(a.b);
writer.endNode();
}
}
public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
throw new NotImplementedException();
}
}
class BConverter implements Converter {
public boolean canConvert(Class clazz) {
return clazz.equals(B.class);
}
public void marshal(Object value, HierarchicalStreamWriter writer, MarshallingContext context) {
System.out.println("Marshalling B!");
B b = (B) value;
if (b.c != null) {
writer.startNode("C");
context.convertAnother(b.c);
writer.endNode();
}
}
public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
throw new NotImplementedException();
}
}
Main
class:
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import sun.reflect.generics.reflectiveObjects.NotImplementedException;
public class XStreamApp {
public static void main(String[] args) {
XStream xStream = new XStream();
xStream.registerConverter(new AConverter());
xStream.registerConverter(new BConverter());
xStream.alias("A", A.class);
System.out.println(xStream.toXML(new A()));
}
}
Prints:
Marshalling A!
Marshalling B!
<A>
<B>
<C/>
</B>
</A>