2013-09-06 8 views
1

У меня очень любопытная ситуация.@XmlЭлемент в коллекции атрибутов только элемент не печатает xsi: 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

xsi:nil будет записан только для предметов в пленке, которые являются null. В вашем примере все элементы в List являются экземплярами Child.

Родитель

При обновлении кода в вашем Parent классе, чтобы добавить нуль в childrenList.

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> 

 Смежные вопросы

  • Нет связанных вопросов^_^