在我当前的 JAXB 编组器应用程序中,我需要有条件地将元素写入 xml 中。
让我看看我能否想出一个例子,但又不会让它听起来像大学作业。
我有一个名为“学生”的班级,其属性称为“优点”和“地位”。并非所有学生都会有优点。只有非新生才会有优点(称为状态的属性给出了学生是否是新生的信息)。当我遍历学生列表并将其编组到 xml 时,我需要有条件地显示 Merit。
如何使用 JAXB 处理 XML 元素的动态创建?我可以想到一个解决方案,将我的学生班级分为 FreshManStudents 和 OtherStudents,并将其他学生的优点定义为 @XMlTransient。仅仅为了 JAXB 目的而重构我的对象是不是有点过分了?
或者,我可以让 getMerit 内部的逻辑让新生的 getMerit 返回 NULL。假设 JAXB 忽略 null 对象,这是解决问题的有效(读起来优雅)方法吗?
感谢您的意见和建议
public class Student {
private Merit merit;
private String status;
public Merit getMerit() {
return merit;
}
public void setMerit(Merit m) {
merit= m;
}
public String getStatus() {
return status;
}
public void setStatus(String s) {
status= s;
}
}
In my current JAXB marshaller application, I need to conditionally write an element into xml.
Let me see if I can think of an example without making it sound like a college homework assignment.
I have a class called Student with properties called merit and status. Not all students will have Merit. Only the non-Freshman students will have merits ( property called status gives the information on whether student is freshman or not). While I traverse through the list of Students and marshall into xml, I need to conditionally display Merit.
How do I handle such dynamic creation of XML elements with JAXB? I can think of a solution where I split my Student class into FreshManStudents and OtherStudents and define merit as @XMlTransient for Otherstudents. Isn't that a bit overkill to refactor my object just for JAXB purpose?
Alternatively, I can have the logic inside getMerit adn have the getMerit return NULL for Freshman students. Assuming JAXB ignores null objects, is that a valid ( read elegant) way to solve the problem?
Thanks for your opinions and suggestions
public class Student {
private Merit merit;
private String status;
public Merit getMerit() {
return merit;
}
public void setMerit(Merit m) {
merit= m;
}
public String getStatus() {
return status;
}
public void setStatus(String s) {
status= s;
}
}
发布评论
评论(1)
快速修复
这可行,并且符合您的问题描述(如下):
关于继承
无论 JAXB 是否参与,您的用例都需要继承:
学生
NonFreshman
了解更多信息
Quick Fix
This would work, and matches your problem description (below):
Regarding Inheritance
Your use case calls for inheritance regardless of JAXB's involvement:
Student
NonFreshman
For More Information