これは長くなるでしょうが、私はいくつかの啓蒙が必要です。私はJAXBを初めて使用するので、寛大になってください。
CourseApp:
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>