如何在jaxb编组期间跳过空字段

时间:2013-11-16 01:24:57

标签: attributes null jaxb marshalling

marshaller是否有办法生成一个跳过任何null属性的新xml文件?所以 像someAttribute =""没有出现在文件中。

由于

1 个答案:

答案 0 :(得分:5)

JAXB (JSR-222)实现不会封送用@XmlAttribute注释的包含空值的字段/属性。

Java模型(根)

import javax.xml.bind.annotation.*;

@XmlRootElement
public class Root {

    private String foo;
    private String bar;

    @XmlAttribute
    public String getFoo() {
        return foo;
    }

    public void setFoo(String foo) {
        this.foo = foo;
    }

    @XmlAttribute(required=true)
    public String getBar() {
        return bar;
    }

    public void setBar(String bar) {
        this.bar = bar;
    }

}

演示代码

import javax.xml.bind.*;

public class Demo {

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

        Root root = new Root();
        root.setFoo(null);
        root.setBar(null);

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(root, System.out);
    }

}

<强>输出

<?xml version="1.0" encoding="UTF-8"?>
<root/>
相关问题