Search code examples
javaxstream

How to omit a tag with Xstream?


I have a class like this:

public class revision{
    long number;
    String comment;

    ... getters and setters
}

and I want the xstream result to give be like this:

<revision comment="value of comment">
  121556
</revision>

However, since number is field it forces me to write it in a <number> tag.

I used this to build the xml:

XStream xstream = new XStream(new DomDriver("UTF-8"));
xstream.useAttributeFor(Revision.class, "comment");

is there a possibility to not show the tag?


Solution

  • You need to register a ToAttributedValueConverter for the revision class. This converter lets you specify a single property of the class that should be mapped to the character content of the element, and all other properties are mapped to attributes on the element. The simplest way to do this is with annotations:

    @XStreamConverter(value=ToAttributedValueConverter.class, strings={"number"})
    public class revision {
      // class body as before
    }
    

    and tell the XStream instance to read the annotations with

    xstream.processAnnotations(revision.class);
    

    With this converter in place you don't need the useAttributeFor call, as the converter will automatically use attributes for everything except the number.

    If you don't want to use annotations then you can configure the converter with a method call on the XStream instance instead, you just have to extract the various helpers from xstream and pass them to the constructor explicitly (the annotation processor passes these things to the converter automatically if it requires them)

    xstream.registerConverter(new ToAttributedValueConverter(
          revision.class, xstream.getMapper(), xstream.getReflectionProvider(),
          xstream.getConverterLookup(), "number"));