在解组操作期间将nil =“true”转换为null

我从服务器接收XML,其架构几乎指定了每个元素:

  

我正在尝试找到一种干净的方法,将我收到的标记为xsi:nil="true"每个元素转换为null,当它被解组到JAXB对象中时。 所以这样的事情:

  

应该导致我的JAXB对象具有值为null的myIntElementName属性,而不是具有nil属性设置为true的JAXBElement对象(或沿着这些行的任何内容)。 我对发送给我使用nillable属性的XML的系统没有任何控制权,所以当我收到它时,我需要在我的结尾转换它。

@XmlElement(的nillable =真)

您只需要在字段/属性上指定@XmlElement(nillable=true)即可获得此行为:

 @XmlElement(nillable=true) private String foo; 

从XML模式生成

下面我将演示如何从XML模式开始生成此映射。

XML Schema(schema.xsd)

            

为什么要获得JAXBElement类型的属性

在模型中生成JAXBElement类型的属性,因为您有一个nillable元素,这是minOccurs="0"JAXBElement的使用允许模型区分缺少的元素(属性为null)和nil="true"的元素的存在(设置了nil标志的JAXBElement)。

  

外部绑定文件(binding.xml)

可以指定外部绑定文件以告知JAXB实现不生成JAXBElement类型的任何属性。 请注意,这将使JAXB无法遍历所有XML文档。

       

XJC电话

下面是如何利用XJC Call中的外部绑定文件的示例

 xjc -b binding.xml schema.xsd 

生成模型(Foo)

生成的模型将如下所示:

 import javax.xml.bind.annotation.*; @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "myStringElementName", "myIntElementName" }) @XmlRootElement(name = "foo") public class Foo { @XmlElement(nillable = true) protected String myStringElementName; @XmlElement(nillable = true) protected Integer myIntElementName; public String getMyStringElementName() { return myStringElementName; } public void setMyStringElementName(String value) { this.myStringElementName = value; } public Integer getMyIntElementName() { return myIntElementName; } public void setMyIntElementName(Integer value) { this.myIntElementName = value; } } 

了解更多信息