问题
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();
}
回答1:
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:
- http://bdoughan.blogspot.com/2010/07/xpath-based-mapping.html
回答2:
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;
}
来源:https://stackoverflow.com/questions/3216943/xstream-flatten-an-object