eze
eze

Reputation: 2422

How do you annotate a java object to add an attribute to a single element using XStream?

I am trying to create a java test using XStream annotations to serialize/deserialize XML like:

<book>
  <title>Hello</title>
  <author>Joe Smith</author>
  <publisher city="Smallville">
      <employees>25</employees>
      <age>15</age>
  </publisher>
  <key type="1">XYZ</key>
</book>

I have most of it working. I have a Book object which uses @XStreamAlias("book"). I create and add a Publisher object to the book with the related alias and using the @XStreamAsAttribute annotation for city.

However, I get stuck when I try to create the object that represents the "key." Basically I need an element named key with an attribute named "type" and the data.

in Book, if I use:

@XStreamAlias("key")
String key;

but that doesn't give me the type attribute (obviously) and if

@XStreamAlias("type")
@XStreamAsAttribute
String type;

I get that attribute added to the Book object (ie,

<book type="1">
 ....
</book>

I haven't found any examples showing how to add an attribute to a single element like this. Does XStream provide a way to do this?

Thanks!

Upvotes: 0

Views: 261

Answers (1)

0E322070
0E322070

Reputation: 762

See http://fahdshariff.blogspot.de/2011/12/using-xstream-to-map-single-element.html (not my site)

The answer adapted from there is:

@XStreamAlias("error")
@XStreamConverter(value=ToAttributedValueConverter.class, strings={"message"})
public class Error {

   String message;
   int code;
}

This will produce the following XML:

<error code="99">This is an error message</error>

Upvotes: 1

Related Questions