I use xstream to marshal an object with nested class to xml string, I write this:
public static String java2xml(Object obj, Class<?> T) {
XStream xstream = new XStream(new StaxDriver());
xstream.processAnnotations(T);
String xml = xstream.toXML(obj);
return xml;
}
Yet I got a <outer-class reference="../.."/>
inside the output string.
the object class is:
public class Foo {
private String foocontent;
private Bar bar;
// getter and setter
public class Bar {
private String blabla;
// getter and setter
}
}
and I make a Foo
with this code:
Foo foo = new Foo();
Bar bar = foo.new Bar();
bar.setBlabla("hello");
foo.setBar(bar);
String fooxml = Xutil.java2xml(foo, Foo.class);
System.out.println(fooxml);
and the whole xml is:
<?xml version="1.0" ?>
<me.mypackage.Foo>
<bar>
<blabla>hello</blabla>
<outer-class reference="../.."/>
</bar>
</me.mypackage.Foo>
Question1: How can I get rid of outer-class
part?
Question2: how to make a pretty-formatted xml string with xstream?
In the previous post I have much emotional comments and make my question unclear, I edit my post and list the help I'm asking, thank you.
Use the PrettyPrintWriter
to get the pretty format along with a StringWriter
as follows:
public static String java2xml(Object obj, Class<?> T) {
XStream xstream = new XStream(new StaxDriver());
xstream.processAnnotations(T);
StringWriter stringWriter = new StringWriter();
xstream.marshal(obj, new PrettyPrintWriter(stringWriter));
return stringWriter.toString();
}
As for the <outer-class reference="../.."/>
issue, if you are not referencing any of Foo
class members from Bar
you can get rid of the <outer-class>
tag by defining the Bar
class as static