我想解组这样的(简化)XML结构:
<parent>
<a>AValue</a>
<b>BValue</b>
<c someAttribute = "true">CValue</c>
</parent>
我知道如何像这样声明C类:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "c", propOrder = {
"someAttribute"
})
public class C{
@XmlValue
private String c;
@XmlAttribute ( name="someAttribute")
private boolean someAttribute;
//getters and setters
}
并使其成为此类的父类成员:
public class Parent{
private String a;
private String b;
private C c;
//getters and setters for c,b,a
}
此作品被发现者,我可以通过C
访问parent.getC().getC();
的值
我的问题是如何实现我不必创建类C
并获得value
的{{1}}和attribute
作为成员的问题(C
的版本,而无需使用新成员以及其他getter和setter来编辑parent
Pojo。
我已经尝试通过侦听器执行此操作,并搜索了类似的结构,但是我没有任何想法。
答案 0 :(得分:1)
I finally figured out how to achieve this.
Its necessary to use the @XmlJavaTypeAdapter
Annotation and mark the C class as an @XmlRootElement
as well as an @XmlAccessorType(XmlAccessType.FIELD)
.
Furthermore one need to use the @XmlTransient
on the getter of the String member which was annotated with @XmlJavaTypeAdapter
.
Full solution:
Class C:
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class C{
@XmlValue
private String c;
@XmlAttribute
private boolean someAttribute;
//getters and setters for both
Class Adapter:
public class Adapter extends XmlAdapter<C, String> {
public String unmarshal(C pC) throws Exception {
//some possible handling with the attribute over pC.getSomeAttribute();
return pC.getC();
}
public C marshal(String pC) throws Exception {
C c = new C();
c.setC(pC)
//some possible handling to set the attribute to c
return c;
}
Class Parent:
public class Parent{
private String a;
private String b;
@XmlJavaTypeAdapter(Adapter.class)
private String c;
@XmlTransient
public String getC() {
return c;
}
//getters and setters for b,a and setter for C
}