13

当我使用 JAXB Marshaller 编组 java 对象时,marshaller 不会为 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>

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

这是编组代码:

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);
4

1 回答 1

17

默认情况下,JAXB (JSR-222)实现不会将属性/元素编组为空值。这对于您的 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 模型

人员培训

由于您正在注释,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>
于 2013-09-24T14:30:42.510 回答