【问题标题】:Force JAXB to Interpret Empty Element as Null not Empty String强制 JAXB 将空元素解释为 Null 而不是空字符串
【发布时间】:2013-09-04 10:24:40
【问题描述】:

我在 XSD 模式中有一个特定元素,我希望 JAXB 将空元素内容视为 null 而不是空字符串。模型类由 XJC 生成。

我见过 this answer for marshalling empty string to null globally,我被 JAXB 的 RI 卡住了,所以我猜这对我不起作用。

鉴于我只需要一个特定元素,我可以采取另一种方法吗?

【问题讨论】:

    标签: java xml jaxb


    【解决方案1】:

    由于这仅适用于一个元素,因此以下是一种可以使其与任何 JAXB 实现一起使用的方法。

    Java 模型

    Foo

    利用@XmlAccessorType 注释设置您的类以使用字段访问。然后将元素对应的字段初始化为""。实现get/set 方法将"" 视为null

    import javax.xml.bind.annotation.*;
    
    @XmlRootElement
    @XmlAccessorType(XmlAccessType.FIELD)
    public class Foo {
    
        private String bar = "";
    
        public String getBar() {
            if(bar.length() == 0) {
                return null;
            } else {
                return bar;
            }
        }
    
        public void setBar(String bar) {
            if(null == bar) {
                this.bar = "";
            } else {
                this.bar = bar;
            }
        }
    
    }
    

    演示代码

    下面是一些演示代码,您可以运行它来查看一切正常。

    input.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <foo>
        <bar/>
    </foo>
    

    演示

    import java.io.File;
    import javax.xml.bind.*;
    
    public class Demo {
    
        public static void main(String[] args) throws Exception {
            JAXBContext jc = JAXBContext.newInstance(Foo.class);
    
            Unmarshaller unmarshaller = jc.createUnmarshaller();
            File xml = new File("src/forum18611294/input.xml");
            Foo foo = (Foo) unmarshaller.unmarshal(xml);
    
            System.out.println(foo.getBar());
    
            Marshaller marshaller = jc.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            marshaller.marshal(foo, System.out);
        }
    
    }
    

    输出

    null
    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <foo>
        <bar></bar>
    </foo>
    

    【讨论】:

    • 感谢您花时间回复 Blaise - 我应该提到模型类是由 XJC 生成的。有没有什么秘制的调料可以达到同样的效果?
    猜你喜欢
    • 2011-08-04
    • 1970-01-01
    • 1970-01-01
    • 2012-07-04
    • 1970-01-01
    • 2013-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多