这会很长,但我需要一些启发。我是 JAXB 的新手,所以请对我宽容。
课程应用:
package Courses;
import java.io.File;
import java.util.ArrayList;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
public class CoursesApp {
public static void main(String[] args) {
Courselist courselist = new Courselist();
courselist.setclassType("Lecture");
courselist.setcourseCode("2002");
courselist.setgroupIndex("1");
courselist.setprofessor("Professor James");
try{
File file = new File("C:\\Courselist.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Courselist.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.marshal(courselist, file);
jaxbMarshaller.marshal(courselist, System.out);
}catch(JAXBException e)
{
e.printStackTrace();
}
}
}
课程表:
package Courses;
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Courselist {
String courseCode;
String classType;
String groupIndex;
String professor;
public String getcourseCode() {
return courseCode;
}
@XmlElement
public void setcourseCode(String courseCode) {
this.courseCode = courseCode;
}
public String getclassType() {
return classType;
}
@XmlElement
public void setclassType(String classType) {
this.classType = classType;
}
public String getgroupIndex() {
return groupIndex;
}
@XmlElement
public void setgroupIndex(String groupIndex) {
this.groupIndex = groupIndex;
}
public String getprofessor() {
return professor;
}
@XmlElement
public void setprofessor(String professor) {
this.professor = professor;
}
}
输出:
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
- <courselist>
<classType>Lecture</classType>
<courseCode>2002</courseCode>
<groupIndex>1</groupIndex>
<professor>Professor James</professor>
</courselist>
我想要的是在同一个 XML 中创建另一个课程列表实例:
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
- <courselist>
-<course>
<classType>Lecture</classType>
<courseCode>2002</courseCode>
<groupIndex>1</groupIndex>
<professor>Professor James</professor>
</course>
-<course>
<classType>Lecture</classType>
<courseCode>2003</courseCode>
<groupIndex>2</groupIndex>
<professor>Professor John</professor>
</course>
</courselist>