Question

I have a very curious situation.

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>

Question 1: Why there is no xsi:nil attribute on those children?

Was it helpful?

Solution

xsi:nil will only be written for items in the cle film that are null. In your example all the items in the List are instances of Child.

Parent

If you update code in your Parent class to add a null into the 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);
    }

Output

The child element corresponding to the null entry will contain the xsi:nil attribute.

<?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>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top