0

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!

eze
  • 2,332
  • 3
  • 19
  • 30

1 Answers1

1

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>
0E322070
  • 762
  • 1
  • 5
  • 15