嗨,我在这里有这些课程: 正如您所看到的,Faculty and Student继承了Persons的名字。 教师和学生都有自己独特的属性
public class Persons{
protected String name;
public Persons(){
this(null);
}
public Persons(String name){
this.name = name;
}
public String getName(){
return this.name;
}
public String setName(String name){
this.name = name;
}
}
public class Student extends Persons{
private String studentId;
public Student(){
this(null,null);
}
public Student(String name,String studentId){
this.name = name;
this.studentId = studentId;
}
}
public class Faculty extends Persons{
private String facultyId;
public Faculty(){
this(null,null);
}
public Faculty(String name,String facultyId){
this.name = name;
this.facultyId = facultyId;
}
}
前提是我有这些XML文件:
<persons>
<student>
<name>Example 1</name>
<studentid>id</studentid>
</student>
<student>
<name>Example 1</name>
<studentid>id</studentid>
</student>
</persons>
和Faculty XML文件:
<persons>
<faculty>
<name>Example 1</name>
<facultyid>id</facultyid>
</faculty>
<faculty>
<name>Example 1</name>
<facultyid>id</facultyid>
</faculty>
</persons>
如何设置用于从xml文件解组的类。我用普通的xml文件做了这个,没有继承,但我只是想知道如果不在两个类中编写相同的属性我会怎么做。谢谢!
答案 0 :(得分:1)
使用JAXB
进行编组或解组时,继承不会使任何内容复杂化。
有一点需要注意:在Java类中,您有名为studentId
和facultyId
的字段(大写字母为I),但在XML中,这些元素以小写字母显示:<studentid>
和<facultyid>
。要么你写的那些相同,要么你必须告诉JAXB什么是XML元素名称存储这些字段的值与这样的注释:
public class Student extends Persons {
@XmlElement(name = "studentid")
private String studentId;
// ... rest of your class
}
public class Faculty extends Persons {
@XmlElement(name = "facultyid")
private String facultyId;
// ... rest of your class
}
现在我们已经告诉了如何在XML文件中表示id字段,我们必须创建包装类来读取学生的集合或者集合的院系:< / p>
public class Students {
@XmlElement(name = "student")
public List<Student> students;
}
public class Faculties {
@XmlElement(name = "faculty")
public List<Faculty> faculties;
}
现在你拥有所需的一切。您可以像这样解组XML文件:
Students students = JAXB.unmarshal(new File("students.xml"), Students.class);
Faculties faculties = JAXB.unmarshal(new File("faculties.xml"), Faculties.class);