这是我的场景。我有一个通用类:
public class Tuple<T> extends ArrayList<T> {
//...
public Tuple(T ...members) {
this(Arrays.asList(members));
}
@XmlElementWrapper(name = "tuple")
@XmlElement(name = "value")
public List<T> getList() {
return this;
}
}
还有一个儿童班:
public class StringTuple extends Tuple<String> {
public StringTuple(String ...members) {
super(members);
}
//explanation of why overriding this method soon ...
@XmlElementWrapper(name = "tuple")
@XmlElement(name = "value")
@Override
public List<String> getList() {
return this;
}
}
这些类在这里引用:
@XmlRootElement(namespace = "iv4e.xml.jaxb.model")
public class Relation {
private Tuple<StringTuple> relationVars;
//...
@XmlElementWrapper(name = "allRelationVars")
@XmlElement(name = "relationVarsList")
public Tuple<StringTuple> getRelationVars() {
return relationVars;
}
}
然后使用如下内容创建一个 Relation 对象:
Relation rel = new Relation();
rel.setRelationVars(new Tuple<StringTuple>(
new StringTuple("RelationshipVar1"), new StringTuple("RelationshipVar2")));
编组该对象后,Xml 输出如下:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns2:relation xmlns:ns2="iv4e.xml.jaxb.model" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="">
<allRelationVars>
<relationVarsList>
<tuple>
<value xmlns:xs="http://www.w3.org/2001/XMLSchema" xsi:type="xs:string">RelationshipVar1</value>
</tuple>
<tuple>
<value>RelationshipVar1</value>
</tuple>
</relationVarsList>
<relationVarsList>
<tuple>
<value xmlns:xs="http://www.w3.org/2001/XMLSchema" xsi:type="xs:string">RelationshipVar2</value>
</tuple>
<tuple>
<value>RelationshipVar2</value>
</tuple>
</relationVarsList>
</allRelationVars>
</ns2:relation>
So the value
元素重复!
现在,类 StringTuple 重写的原因List<T> getList()
with List<String> getList()
是避免产生烦人的xmlns:xs
列表中每个成员的属性(value
xml 文档中的元素)。
但是列表中的每个成员都会在输出中显示两次。显然,这是因为重写的父方法和子方法都用注释@XmlElement
。
所以我的主要问题是:有一种方法可以忽略用注释覆盖的方法@XmlElement
在贾克斯布? (考虑到覆盖方法也用注释@XmlElement
)
我发现一篇旧帖子报告了非常相似的问题:http://old.nabble.com/@XmlElement-on-overridden-methods-td19101616.html http://old.nabble.com/@XmlElement-on-overridden-methods-td19101616.html,但我还没有找到任何解决方案。
另请注意,添加@XmlTransient
注释到getList
父类的方法(Tuple<T>
) 可以解决这个问题,但会产生其他问题,因为父类不是抽象的,并且在其他上下文中单独使用。
一方面的次要问题:是否可以声明xmlns:xs
属性出现在根节点而不是 - 烦人 - 出现在每个需要它的节点中?我知道这可以通过NamespacePrefixMapper
类,但由于它是一个非标准的 SUN 内部类,我宁愿使用更独立于实现的方法。
预先感谢您的任何反馈!