开发者

JAXB displaying an object's content without adding a node for the object

I am using JAXB with annotations. I want the creditcard info to be displayed without the creditcardinfo node being displayed. FYI CreditCardInfo is an object of complex type.

@XmlRootElement
public Class Notification{
private String notifDate;
private CreditCardInfo ccI开发者_StackOverflow中文版nfo;
}

public Class CreditCardInfo{
private int ccNum;
private String expiryMonth;
}

Desired output

<notification>
<date>04/29/11</date>
<ccNum>3456</ccNum>
<expiry_month>November</expiry_month>
</notification>

Regards, -Anand


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

  • http://bdoughan.blogspot.com/2010/07/xpath-based-mapping.html
  • http://bdoughan.blogspot.com/2010/09/xpath-based-mapping-geocode-example.html
  • http://bdoughan.blogspot.com/2011/03/map-to-element-based-on-attribute-value.html
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜