JAXB Marshaller没有值为null的元素

时间:2013-09-24 13:57:23

标签: java xml jaxb

当我使用JAXB Marshaller编组java对象时,编组器不会为java对象中的空文件创建空元素。例如,我有一个以下的java对象:

public class PersonTraining {

    @XmlElement(name = "Val1", required = true)
    protected BigDecimal val1;
    @XmlElement(name = "Val2", required = true, nillable = true)
    protected BigDecimal val2;
    @XmlElement(name = "Val3", required = true, nillable = true)
    @XmlSchemaType(name = "dateTime")
    protected XMLGregorianCalendar val3;
}

当我获取此对象的实例并编组为XML时,我得到以下内容(这是因为我没有为Val2设置值):

<PersonTraining>
      <Val1>1</Val1>
       <Val3>2010-01-01T00:00:00.0-05:00</Val3>
 </PersonTraining>

但是,我原本预计会有来自编组操作的结果(事实上,我特别需要元素,以便可以针对XSD验证XML)

<PersonTraining>
      <Val1>1</Val1>
      <Val2></Val2>
       <Val3>2010-01-01T00:00:00.0-05:00</Val3>
 </PersonTraining>

请让我知道我需要设置哪个选项,以便对象属性中的空值也可以编组,并作为空/ null元素返回。

以下是编组代码:

StringWriter sw = new StringWriter();
JAXBContext jc = JAXBContext.newInstance("person_training");   
Marshaller m = jc.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
m.marshal(ptl, sw);

1 个答案:

答案 0 :(得分:11)

默认情况下,JAXB (JSR-222)实现不会为null值封送属性/元素。这将适用于Java模型中的以下字段。

@XmlElement(name = "Val1", required = true)
protected BigDecimal val1;

您可以通过在nillable=true注释上指定@XmlElement来覆盖此行为,就像您在此处所做的那样:

@XmlElement(name = "Val2", required = true, nillable = true)
protected BigDecimal val2;

这将导致xsi:nil="true"属性具有杠杆作用:

<Val2 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>

了解更多信息:


Java模型

<强> PersonTraining

由于您要对fields进行注释,因此应确保在类或包级别指定@XmlAccessorType(XmlAccessType.FIELD)(请参阅:http://blog.bdoughan.com/2011/06/using-jaxbs-xmlaccessortype-to.html)。

import java.math.BigDecimal;
import javax.xml.bind.annotation.*;
import javax.xml.datatype.XMLGregorianCalendar;

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class PersonTraining {

    @XmlElement(name = "Val1", required = true)
    protected BigDecimal val1;
    @XmlElement(name = "Val2", required = true, nillable = true)
    protected BigDecimal val2;
    @XmlElement(name = "Val3", required = true, nillable = true)
    @XmlSchemaType(name = "dateTime")
    protected XMLGregorianCalendar val3;

}

演示代码

<强>演示

import javax.xml.bind.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(PersonTraining.class);

        PersonTraining pt = new PersonTraining();

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(pt, System.out);
    }

}

<强>输出

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<personTraining>
    <Val2 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>
    <Val3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>
</personTraining>