问题
I would like to serialize an object to an XML of this form with XStream.
<node att="value">text</node>
There already is a solution for this in StackOverflow here: XStream : node with attributes and text node? but it won't work for me since I am restricted to XStream 1.3.1.
I found
@XStreamConverter(value=ToAttributedValueConverter.class, strings={"content"})
which does exactly what I want in a simple way but it is not available in XStream 1.3.1.
Is there a nicer way to solve this issue with 1.3.1 version of XStream?
回答1:
It's possible with some hacks. The main idia is to use a modified ToAttributedValueConverter
from 1.4.7.
- Copy
ToAttributedValueConverter
into your package - Copy
UseAttributeForEnumMapper
into your package Replace
ToAttributedValueConverter#fieldIsEqual
as follows:private boolean fieldIsEqual(FastField field) { return valueField.getName().equals(field.getName()) && valueField.getDeclaringClass().getName() .equals(field.getDeclaringClass().getName()); }
Replace the Constructor in
UseAttributeForEnumMapper
as follows:public UseAttributeForEnumMapper(Mapper wrapped) { super(wrapped, null); }
It is not possible to use the @XStreamConverter
annotation, becouse the ToAttributedValueConverter
has a constrcutor that needs some extra information, like the value field. But you can use XStream#registerConverter
alternativly. So your class have to look like:
@XStreamAlias("node")
public class Node {
private String attr;
private String content;
public void setAttr(String attr) { this.attr = attr; }
public String getAttr() { return attr; }
public void setContent(String content) { this.content = content; }
public String getContent() { return content; }
}
And a example that shows how to configure xstream for this converter:
public static void main(String[] args) {
final Node node = new Node();
node.setAttr("value");
node.setContent("text");
final XStream xstream = new XStream();
configureXStream(xstream);
final String xml = xstream.toXML(node);
System.out.println(xml);
final Node node2 = (Node) xstream.fromXML(xml);
System.out.println("attr: " + node2.getAttr());
System.out.println("content: " + node2.getContent());
}
private static void configureXStream(final XStream xstream) {
xstream.autodetectAnnotations(true);
final Mapper mapper = xstream.getMapper();
final ReflectionProvider reflectionProvider = xstream
.getReflectionProvider();
final ConverterLookup lookup = xstream.getConverterLookup();
final Converter converter = new ToAttributedValueConverter(Node.class,
mapper, reflectionProvider, lookup, "content");
xstream.registerConverter(converter);
}
This program prints out:
<node attr="value">text</node>
attr: value
content: text
来源:https://stackoverflow.com/questions/23570817/xstream-node-with-attributes-and-text-node-in-xstream-1-3-1