1

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

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

4

1 回答 1

1

xsi:nil只会为 cle 电影中的项目编写null。在您的示例中,所有项目List都是Child.

家长

如果您更新Parent类中的代码以将 null 添加到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>
于 2013-09-06T10:36:45.817 回答