我想使用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;
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;
}
中的代码
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>