JAXB显示对象的内容而不为对象添加节点

时间:2011-05-03 17:09:17

标签: annotations jaxb

我正在使用带注释的JAXB。我希望显示信用卡信息,而不显示creditcardinfo节点。 FYI CreditCardInfo是一个复杂类型的对象。

@XmlRootElement
public Class Notification{
private String notifDate;
private CreditCardInfo ccInfo;
}

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

期望的输出

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

此致 -Anand

1 个答案:

答案 0 :(得分:0)

您可以使用@XmlPath中的EclipseLink JAXB (MOXy)扩展程序来处理此用例。注意:我是MOXy领导。

<强>通知

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;

}

<强>演示

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

要将MOXy用作JAXB提供程序,您需要在与模型类相同的包中添加名为jaxb.properties的文件,并使用以下条目:

javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory

<强>输入/输出

<?xml version="1.0" encoding="UTF-8"?>
<notification>
   <date>04/29/11</date>
   <ccNum>3456</ccNum>
   <expiry_month>November</expiry_month>
</notification>

了解更多信息