小编典典
您可以执行以下操作。通过利用,@XmlElementWrapper您可以减少所需的类数量:
福斯特之家
package nov18;
import java.util.List;
import javax.xml.bind.annotation.*;
@XmlRootElement(name="FosterHome")
@XmlAccessorType(XmlAccessType.FIELD)
public class FosterHome {
@XmlElement(name="Orphanage")
private String orphanage;
@XmlElement(name="Location")
private String location;
@XmlElementWrapper(name="Families")
@XmlElement(name="Family")
private List families;
@XmlElementWrapper(name="RemainingChildList")
@XmlElement(name="ChildID")
private List remainingChildren;
}
家庭
package nov18;
import java.util.List;
import javax.xml.bind.annotation.*;
@XmlAccessorType(XmlAccessType.FIELD)
public class Family {
@XmlElement(name="ParentID")
private String parentID;
@XmlElementWrapper(name="ChildList")
@XmlElement(name="ChildID")
private List childList;
}
演示版
package nov18;
import java.io.File;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(FosterHome.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
FosterHome fosterHome = (FosterHome) unmarshaller.unmarshal(new File("src/nov18/input.xml"));
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(fosterHome, System.out);
}
}
输入输出
Happy Days Daycare
Apple Street
Adams
Child1
Child2
Adams
Child3
Child4
Child5
Child6
想要查询更多的信息
更新
有没有简单的方法可以迭代/打印出Family类中的所有ChildID?
您可以执行以下操作:
for(Family family : fosterHome.getFamilies()) {
System.out.println(family.getParentID());
for(String childID : family.getChildList()) {
System.out.println(" " + childID);
}
}
2020-09-15
本文介绍如何利用Java的JAXB库中的@XmlElementWrapper注解来减少XML绑定所需的类数量。通过示例展示了如何组织FosterHome、Family类以及它们之间的关系,并提供了代码示例进行XML的序列化和反序列化操作。此外,还提供了遍历并打印Family类中所有ChildID的方法。
1万+

被折叠的 条评论
为什么被折叠?



