Jaxb marshaller总是写xsi:nil(即使在@XmlElement(required = false,nillable = true)时) [英] Jaxb marshaller always writes xsi:nil (even when @XmlElement(required=false, nillable=true))

查看:877
本文介绍了Jaxb marshaller总是写xsi:nil(即使在@XmlElement(required = false,nillable = true)时)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用 @XmlElement(required = false,nillable = true)注释的java属性。当对象被编组为xml时,它总是以 xsi:nil =true属性输出。

I have a java property annotated with @XmlElement(required=false, nillable=true). When the object is marshalled to xml, it is always outputted with the xsi:nil="true" attribute.

是否有一个jaxbcontext / marshaller选项来指示编组人员不要编写元素,而不是用 xsi:nil 写它?

Is there a jaxbcontext/marshaller option to direct the marshaller not to write the element, rather than write it with xsi:nil?

我已经找到了答案,并且看了一下代码,afaics,如果 xsi:nil > nillable = true 。我错过了什么?

I've looked for answers to this and also had a look at the code, afaics, it will always write xsi:nil if nillable = true. Am I missing something?

推荐答案

如果该属性使用 @XmlElement注释(required = false,nillable = true)并且值为null,它将以 xsi:nil =true写出。

If the property is annotated with @XmlElement(required=false, nillable=true) and the value is null it will be written out with xsi:nil="true".

如果只用 @XmlElement 注释它,你将得到你想要的行为。

If you annotate it with just @XmlElement you will get the behaviour you are looking for.

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 javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement;

示例

给出以下类:

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

    @XmlElement(nillable=true, required=true)
    private String elementNillableRequired;

    @XmlElement(nillable=true)
    private String elementNillbable;

    @XmlElement(required=true)
    private String elementRequired;

    @XmlElement
    private String element;

}

此演示代码:

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;

public class Demo {

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

        Root root = new Root();

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        marshaller.marshal(root, System.out);
    }

}

结果将是:

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

这篇关于Jaxb marshaller总是写xsi:nil(即使在@XmlElement(required = false,nillable = true)时)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆