使用默认值初始化的

使用默认值初始化的

本文介绍了使用默认值初始化的 JAXB 对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JAXB 没有什么问题.

给定:

  • Java 1.5;来自 jaxws-2_0 的 jaxb -jars.
  • .xsd 方案和生成的 JAXB 类.
  • .xsd 中的每个简单元素都有默认值.结果类成员有这样的注释"@XmlElement(name = "cl_fname", required = true, defaultValue = "[______]")"

必填

获取java对象(根元素),它完全代表xml和默认值初始化的每个成员.

Get java object (root element) which fully represent xml and every member initialized by default values.

当我尝试在没有明确设置值的情况下编组 xml 时,默认值没有意义......有没有办法在不自定义生成的类的情况下编组填充有默认值的 xml?

when I try to marshall xml without explicitly setting values, default values doesn't make sence... is there any way to marshall xml populated with default values without customization of generated classes?

.xsd 示例:

<xs:element name="document">
    <xs:complexType>
        <xs:sequence>
            <xs:element ref="d_int"/>
            <xs:element ref="d_double"/>
            <xs:element ref="d_string"/>
        </xs:sequence>
    </xs:complexType>
</xs:element>

<xs:element name="d_int" type="xs:int" default="-1"/>
<xs:element name="d_double" type="xs:double" default="-1.0"/>
<xs:element name="d_string" type="xs:string" default="false"/>

和java类:

public class Document {
    @XmlElement(name = "d_int", defaultValue = "-1")
    protected int dInt;
    @XmlElement(name = "d_double", defaultValue = "-1.0")
    protected double dDouble;
    @XmlElement(name = "d_string", required = true, defaultValue = "Default")
    protected String dString;
...
}

推荐答案

注解中的默认值仅在解组后有效.
解组这个

default value that is in annotations works only after unmarshalling.
unmarshal this

<document>
   <d_int/>
   <d_double/>
   <d_string/>
</document>

您将获得具有默认值(-1、-1.0、默认")的对象

and you will get object with default values (-1, -1.0, "Default")

如果你想设置默认值来编组,你应该这样做

If you want set default values to marshalling, you should do this

public class Document {
    @XmlElement(name = "d_int", defaultValue = "-1")
    protected int dInt = 100;
    @XmlElement(name = "d_double", defaultValue = "-1.0")
    protected double dDouble = -100;
    @XmlElement(name = "d_string", required = true, defaultValue = "Default")
    protected String dString = "def";
...
}

jaxb 只为解组生成默认值

jaxb generate default values only for unmarshalling

这篇关于使用默认值初始化的 JAXB 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 19:53