JAXB is a handy technology that easily transforms Java objects to XML documents and vice versa.
Define the object
There is a business need to define and use messages. For every message we need:
- The sender
- The receiver
- The actual message
- A unique identification
@XmlRootElement
public class Message {
private String from;
private String to;
private String text;
private int id;
}
API: XmlRootElement
We would like the id to be an attribute of the root element.
@XmlRootElement
public class Message {
private String from;
private String to;
private String text;
private int id;
@XmlAttribute
public void setId(int id) {
this.id = id;
}
}
API: XmlAttribute
Here’s the complete class.
/** * A message. */ @XmlRootElement public class Message { /** * The sender. */ private String from; /** * The receiver. */ private String to; /** * A unique identification. */ private int id; /** * The actual message. */ private String text; /** * Default contstructor. */ public Message() { } public String getFrom() { return from; } public void setFrom(String from) { this.from = from; } public String getTo() { return to; } public void setTo(String to) { this.to = to; } public String getText() { return text; } public void setText(String text) { this.text = text; } public int getId() { return id; } @XmlAttribute public void setId(int id) { this.id = id; } public String toString() { return String.format("Message[id=%s, from=%s, to=%s, text=%s]", id, from, to, text); } }
Write the object to XML
In order to write/serialize/marshal the Java object to XML follow these simple steps.
Message message = new Message();
message.setFrom("Nikos");
message.setTo("Sofia");
message.setText("Hello from JAXB!");
message.setId(123);
// Create a JAXB context and a marshaller
JAXBContext context = JAXBContext.newInstance(Message.class);
Marshaller handler = context.createMarshaller();
// Set the output in pretty format
handler.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
// Make the actual serialization
handler.marshal(message, new File("/output.xml"));
API: JAXBContext, Marshaller
Get the object from XML
It is equally easy to read/deserialize/unmarshal the Java object from its XML representation.
// Create a JAXB context and an unmarshaller JAXBContext context = JAXBContext.newInstance(Message.class); Unmarshaller handler = context.createUnmarshaller(); // Get the object Message msg = (Message)handler.unmarshal(new File("/output.xml"));
API: Unmarshaller
Summary
The output should be
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <message id="123"> <from>Nikos</from> <text>Hello from JAXB!</text> <to>Sofia</to> </message>
Java Architecture for XML-Binding is part of core Java since Standard Edition 6. Moreover, it is a basic component of Java Web Services.
hi nice and quick intro on JAXB thanx for that
well can u explain JAXP what is this basically and for what and how to use it..
Reblogged this on Zeeshan Akhter.
Good one Nikos, very Helpful.