@XmlElement对属性集合的唯一元素不会打印xsi:nil

时间:2013-09-06 08:33:19

标签: jaxb jaxb2 xml-nil

我有一个非常奇怪的情况。

public class Child {

    @XmlAttribute
    public String name;
}
@XmlRootElement
public class Parent {

    public static void main(final String[] args) throws Exception {
        final Parent parent = new Parent();
        parent.children = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            final Child child = new Child();
            child.name = Integer.toString(i);
            parent.children.add(child);
        }
        final JAXBContext context = JAXBContext.newInstance(Parent.class);
        final Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        marshaller.marshal(parent, System.out);
    }

    @XmlElement(name = "child", nillable = true)
    public List<Child> children;
}
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<parent>
    <child name="0"/> <!-- xsi:nil expected -->
    <child name="1"/>
    <child name="2"/>
</parent>

问题1:为什么xsi:nil上没有children属性?

1 个答案:

答案 0 :(得分:1)

xsi:nil仅针对电影null中的项目撰写。在您的示例中,List中的所有项都是Child的实例。

<强>父

如果您更新Parent课程中的代码,则会在children List中添加空格。

    public static void main(final String[] args) throws Exception {
        final Parent parent = new Parent();
        parent.children = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            final Child child = new Child();
            child.name = Integer.toString(i);
            parent.children.add(child);
        }

        // UPDATE - Add a null entry to the List
        parent.children.add(null);

        final JAXBContext context = JAXBContext.newInstance(Parent.class);
        final Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        marshaller.marshal(parent, System.out);
    }

<强>输出

child条目对应的null元素将包含xsi:nil属性。

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<parent>
    <child name="0"/>
    <child name="1"/>
    <child name="2"/>
    <child xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>
</parent>