我有一个非常奇怪的情况。
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
属性?
答案 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>