You could use the @XmlPath extension in EclipseLink JAXB (MOXy) to handle this use case. Note: I'm the MOXy lead.
Notification
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import org.eclipse.persistence.oxm.annotations.XmlPath;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Notification{
@XmlElement(name="date")
private String notifDate;
@XmlPath(".")
private CreditCardInfo ccInfo;
}
CreditCardInfo
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
@XmlAccessorType(XmlAccessType.FIELD)
public class CreditCardInfo{
private int ccNum;
@XmlElement(name="expiry_month")
private String expiryMonth;
}
Demo
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Notification.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
Notification notification = (Notification) unmarshaller.unmarshal(new File("input.xml"));
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(notification, System.out);
}
}
jaxb.properties
To use MOXy as your JAXB provider you need to add a file named jaxb.properties in the same package as your model classes with the following entry:
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
Input/Output
<?xml version="1.0" encoding="UTF-8"?>
<notification>
<date>04/29/11</date>
<ccNum>3456</ccNum>
<expiry_month>November</expiry_month>
</notification>
For More Information