我想使用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>
答案 0 :(得分:0)
尝试在List服务上使用@XmlElementWrapper注释:
@XmlElementWrapper
@XmlElement(name="service")
private List<Service> services=new ArrayList<>();