18

I would like to serialize an object to an XML of this form with XStream.

<node att="value">text</node>

The value of the node (text) is a field on the serialized object, as well as the att attribute. Is this possible without writing a converter for this object?

Thanks!

4

4 回答 4

19

您可以使用预定义的转换器。

@XStreamAlias("node")
@XStreamConverter(value=ToAttributedValueConverter.class, strings={"text"})
class Node {
  private String att;
  private String text;
}   

XStream Annotations Tutorial还说对于att属性:

请注意,不需要 XStreamAsAttribute 注释。转换器隐含地假定它。

于 2012-01-20T13:08:27.570 回答
7

写一个转换器,应该是类似代码片段的东西

class FieldDtoConvertor implements Converter {
    @SuppressWarnings("unchecked")
    public boolean canConvert(final Class clazz) {
        return clazz.equals(FieldDto.class);
    }

    public void marshal(final Object value,
            final HierarchicalStreamWriter writer,
            final MarshallingContext context) {
        final FieldDto fieldDto = (FieldDto) value;
        writer.addAttribute(fieldDto.getAttributeName(), fieldDto.getAttributeValue());     
    }
}

在使用 XStream 时,注册转换器

final XStream stream = new XStream(new DomDriver());
stream.registerConverter(new FieldDtoConvertor());
于 2009-11-13T06:36:43.833 回答
0

这在 JAXB 中要容易得多

@XmlRootElement
public class Node {

    @XmlAttribute
    String att;

    @XmlValue
    String value;    

}
于 2010-08-20T13:25:31.840 回答
0

只是另一种方式:

   @XStreamAlias("My")
   private static class My {
      private String field;
   }

   XStream xStream = new XStream();
   xStream.autodetectAnnotations(true);
   xStream.useAttributeFor(My.class, "field");
于 2017-07-29T23:25:08.113 回答