Message Object
Our message object needs to represent 3 things:
- Who the message is from.
- Who the message is to.
- The body of the message.
package message;
import javax.xml.bind.annotation.*;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Message {
@XmlAttribute
private String to;
@XmlAttribute
private String from;
@XmlAnyElement(lax=true)
private Object body;
}Customer PayloadThe Customer class will be the root type for the body of the message when the payload corresponds to customer information, so we need to annotate it as @XmlRootElement.
package customer;
import javax.xml.bind.annotation.*;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Customer {
private String name;
private Address address;
}
package customer;
import javax.xml.bind.annotation.*;
@XmlAccessorType(XmlAccessType.FIELD)
public class Address {
private String street;
private String city;
}
Product Payload
The Product class will be the root type for the body of the message when the payload corresponds to product information, so we need to annotate it with @XmlRootElement.
package product;
import javax.xml.bind.annotation.*;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Product {
private String name;
}
JAXBContext.newInstance("message:customer:product");Address Customer
JAXBContext.newInstance("message:customer:product:order");<message to="john@example.com" from="jane@example.com">
<customer>
<name>Sue Smith</name>
<address>
<street>123 A Street</street>
<city>Any Town</city>
</address>
</customer>
</message>import java.io.File;
import javax.xml.bind.*;
import message.Message;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance("message:customer:product");
Unmarshaller unmarshaller = jc.createUnmarshaller();
File file = new File("input.xml");
Message message = (Message) unmarshaller.unmarshal(file);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(message, System.out);
}
}
4 comments: