我正在尝试创建一个XML文档,其结构比我见过的其他示例更复杂。这是我的尝试,使用三个类:
@XmlRootElement(name = "Band")
@XmlType(propOrder = { "x" })
public class Band {
private int x;
public Band() {
x = 0;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
}
@XmlRootElement(name = "Program")
@XmlType(propOrder = { "numBands" , "programName", "bandList"})
public class Program {
private int numBands;
private String programName;
private ArrayList<Band> bandlist;
public void Program() {
Band band1 = new Band();
band1.setX(14);
bandlist.add(band1);
Band band2 = new Band();
band2.setX(24);
bandlist.add(band2);
}
public void setNumBands(int nb) {
numBands = nb;
}
@XmlElement(name = "numBands")
public int getNumBands() {
return numBands;
}
public void setProgramName(String pn) {
programName = pn;
}
@XmlElement(name = "programName")
public String getProgramName() {
return programName;
}
public void setBandList(ArrayList<Band> bl) {
bandlist = bl;
}
@XmlElementWrapper(name = "bandlist")
public ArrayList<Band> getBandList() {
return bandlist;
}
}
@XmlRootElement()
@XmlType(propOrder = {"programList"})
public class ProgramList {
private ArrayList<Program> programlist;
public void ProgramList() {
Program program1 = new Program();
program1.setNumBands(2);
program1.setProgramName("Program 1");
programlist.add(program1);
Program program2 = new Program();
program2.setNumBands(2);
program2.setProgramName("Program 2");
programlist.add(program2);
}
public void setProgramList(ArrayList<Program> programlist) {
this.programlist = programlist;
}
@XmlElementWrapper(name = "programlist")
public ArrayList<Program> getProgramList() {
return programlist;
}
}
private void writeXML() throws JAXBException, IOException {
ProgramList pl = new ProgramList();
JAXBContext context = JAXBContext.newInstance(ProgramList.class);
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
m.marshal(pl, new File("program.xml"));
}
这一切都可以正常编译,并且无异常运行。但XML文档看起来像这样:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ProgramList/>
不是我的预期。我期望ProgramList对象的实例化会创建两个程序,每个程序有两个带,并且整个过程最终都会出现在XML文件中。
我这样做是错的吗?
我也试过这一行:
JAXBContext context = JAXBContext.newInstance(new Class[] {ProgramList.class, Program.class, Band.class});
同样的结果。
答案 0 :(得分:1)
以下不是构造函数,因为它具有void
返回类型。它只是一个与构造函数同名的方法。这意味着此逻辑未运行以填充对象模型。
public void ProgramList() {
Program program1 = new Program();
program1.setNumBands(2);
program1.setProgramName("Program 1");
programlist.add(program1);
Program program2 = new Program();
program2.setNumBands(2);
program2.setProgramName("Program 2");
programlist.add(program2);
}
应该是:
public ProgramList() {
programlist = new ArrayList<Program>(2);
Program program1 = new Program();
program1.setNumBands(2);
program1.setProgramName("Program 1");
programlist.add(program1);
Program program2 = new Program();
program2.setNumBands(2);
program2.setProgramName("Program 2");
programlist.add(program2);
}
注意:由于JAXB是异常配置,因此您添加了许多不必要的注释。以下内容应该有所帮助: