tags:

views:

89

answers:

3

I've read a time ago about generate xml from Java using annotations, but I'm not finding a simple example now.

If I want to make a xml file like:

<x:element uid="asdf">value</x:element>

from my java class:

public class Element {
  private String uid = "asdf";
  private String value = "value";
}

Which annotations should I use to perform that? (I have a xml-schema, if this helps the generation)

--update

The javax.xml.bind.annotation package have the annotations, "but I still haven't found what I'm looking for": an exemple of usage.. :)

+1  A: 

There are various tools that you can use to do this. XStream (http://xstream.codehaus.org/) is a reasonably easy tool to use that allows you to use annotations to determine the schema of XML that is created.

nojo
I would like JDK included tools
Tom Brito
You'll have to go outside the JDK, What you are looking for is a tool that customizes serialization--I think that's what XStream does. Instead of serialization going to a binary unreadable mess it goes to XML. Of course that might not give you exactly what you are looking for, but it's the closest thing i can think of.
Bill K
doesn't JAXB, for example, do the work?
Tom Brito
@Brito: yes, JAXB does exactly that. XStream is not strictly necessary (it's a third-party library that existed before JAXB, if I remember correctly).
Joachim Sauer
@Joachim - JAXB was created first.
Blaise Doughan
@Blaise: interesting, I didn't know that.
Joachim Sauer
A: 

For the benefit of anyone else hitting this thread, I imagine you did the following:

@XmlRootElement
public class Element { 

  @XmlAttribute
  private String uid = "asdf"; 

  @XmlValue
  private String value = "value"; 
} 
Blaise Doughan