tags:

views:

560

answers:

3

Hi, 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!

A: 

I'm pretty sure that you need to write a converter. Having said that it shouldn't be hard.

Michael Rutherfurd
+2  A: 

write a convertor, it should be something similar to the code snippet

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());  
    }
}

And while using XStream,register the convertor

final XStream stream = new XStream(new DomDriver());
stream.registerConverter(new FieldDtoConvertor());
Kiru
yes, this looks like what I've done, but I've added a writer.setValue(fieldDto.getText()) to set the node's text.
Subb
yes Subb, it is required to set the node value, missed it in the snippet
Kiru
A: 

This is much easier in JAXB

@XmlRootElement
public class Node {

    @XmlAttribute
    String att;

    @XmlValue
    String value;    

}
Blaise Doughan
Blaise Doughan