[英]Marshal an attribute as a type of list like nested root element using JAXB
我想使用JAXB API保存醫院列表,每個醫院都有自己的服務列表。 為此,我實現了以下課程
public class Wrapper<T> {
private List<T> items = new ArrayList<T>();
@XmlAnyElement(lax=true)
public List<T> getItems() {
return items;
}
}
/*************************************/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name="hopital")
public class Hopital {
private int id;
private String nom,adresse,categorie="";
@XmlElement(name="service")
private List<Service> services=new ArrayList<>();
private static List<Hopital> liste=new ArrayList<>();
static File springDir;
static JAXBContext context;
static BufferedWriter writer = null;
//constructeurs
//getters and setters
public static void addHopital(Hopital ... hops) throws Exception{
File hfile = new File("hopitaux.xml");
Wrapper<Hopital> hopitaux = new Wrapper<Hopital>();
for (int i = 0; i < hops.length; i++) {
hopitaux.getItems().add(hops[i]);
}
writer = new BufferedWriter(new FileWriter(hfile));
context =JAXBContext.newInstance(Wrapper.class,Hopital.class,Service.class);
JAXBElement<Wrapper> element=new JAXBElement<Wrapper>(new
QName("hopitaux"), Wrapper.class,hopitaux);
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_ENCODING, "iso-8859-15");
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
m.marshal(element, writer);
writer.close();
}
}
/*************************************/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name="service")
public class Service {
private int numero;
private String libelle;
//constructeurs
//getters and setters
}
/*************************************/
Hopital.addHopital()
的代碼可以正常工作,並以以下結構提供xml輸出:
<?xml version="1.0" encoding="iso-8859-15" standalone="yes"?>
<hopitaux>
<hopital>
<id>0</id>
<nom>A</nom>
<adresse>aaaaaaaa</adresse>
<categorie></categorie>
<service>
<numero>1</numero>
<libelle>car</libelle>
</service>
<service>
<numero>1</numero>
<libelle>chg</libelle>
</service>
</hopital>
<hopital>
.....
</hopital>
</hopitaux>
但我想通過具有此服務列表的根元素來獲得以下結構:
<hopitaux>
<hopital>
<id>0</id>
<nom>A</nom>
<adresse>aaaaaaaa</adresse>
<categorie></categorie>
<services>
<service>
<numero>1</numero>
<libelle>car</libelle>
</service>
<service>
<numero>1</numero>
<libelle>chg</libelle>
</service>
</services>
</hopital>
<hopital>
.....
</hopital>
</hopitaux>
</pre>
嘗試在List服務上使用@XmlElementWrapper批注:
@XmlElementWrapper
@XmlElement(name="service")
private List<Service> services=new ArrayList<>();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.