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

查看:49
本文介绍了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,如果 nillable = true,它总是会写 xsi:nil.我错过了什么吗?

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.

导入 javax.xml.bind.annotation.XmlAccessType;导入 javax.xml.bind.annotation.XmlAccessorType;导入 javax.xml.bind.annotation.XmlElement;导入 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天全站免登陆