我使用 JDOM 创建了一个 XML 文件(来自 Object)并且它可以工作,但是我无法让一个嵌套元素(Teachers)正常工作。
这是创建文件的方法:
public void writeFileUsingJDOM(List<Activity> activityList, String fileName) throws IOException {
Document doc = new Document();
doc.setRootElement(new Element("Activities", Namespace.getNamespace("http://www.jana.com/activities")));
for(Activity act : activityList) {
Element activity = new Element("Activity");
activity.setAttribute("id", act.getActivityId().toString());
activity.addContent(new Element("ActivityDescription").setText(act.getActivityDescription()));
activity.addContent(new Element("CourseDescription").setText(act.getCourse().getCourseDescription()));
// retrieve the list of teachers based on activity id
List<Teacher> teacherList = teacherService.getAll(act.getActivityId());
activity.addContent(new Element("Teachers")); // THIS IS WRONG!
for(Teacher teach : teacherList) {
activity.addContent(new Element("Teacher").addContent(new Element("Name").setText(teach.getFirstName() + " " + teach.getLastName())));
}
activity.addContent(new Element("SubmissionDate").setText(act.getSubmissionDate()));
activity.addContent(new Element("Score").setText(act.getScore().toString()));
activity.addContent(new Element("Note").setText(act.getNote()));
doc.getRootElement().addContent(activity);
}
//write JDOM document to file
XMLOutputter xmlOutputter = new XMLOutputter(Format.getPrettyFormat());
xmlOutputter.output(doc, new FileOutputStream(fileName));
}
我在我创建的 XML 文件中得到了这个:
<?xml version="1.0" encoding="UTF-8"?>
...
<Activity xmlns="" id="82">
<ActivityDescription>Some other activity</ActivityDescription>
<CourseDescription>Some other course</CourseDescription>
<Teachers /> <!-- THIS IS THE PROBLEM! Teacher elements should be inside Teachers element -->
<Teacher>
<Name>Douglas Richardson</Name>
</Teacher>
<Teacher>
<Name>Kieran Pittman</Name>
</Teacher>
<SubmissionDate>01/21/2014</SubmissionDate>
<Score>30</Score>
<Note>Some other note</Note>
</Activity>
...
</Activities>
它应该是这样的:
<Teachers>
<Teacher>
<Name>Douglas Richardson</Name>
</Teacher>
<Teacher>
<Name>Kieran Pittman</Name>
</Teacher>
</Teachers>
谁能告诉我如何实现这一目标?谢谢...