我想实现类似 this 的目标.
<zoo>
<lion> ... </lion>
<dog> ... </dog>
</zoo>
我这里有这门课。
public class MainGroup {
private List<Widget> widgets;
@XmlAnyElement
public List<Widget> getWidgets() {
return widgets;
}
public void setWidgets(List<Widget> widgets) {
this.widgets = widgets;
}
}
并且这个 Widget 父类(super class)有 Button、Combobox 等子类...... 我想实现这样的目标。
<MainGroup>
<Button>...</Button>
<Combo>...</Combo>
</MainGroup>
我有这个异常(exception)
[com.sun.istack.internal.SAXException2: class com.test.Button nor any of its super
class is known to this context.
我尝试添加@XmlElementRef,但它仍然无法正常工作。
@XmlElementRefs({
@XmlElementRef(name="Button", type=Button.class),
@XmlElementRef(name="Combo", type=Combo.class)
})
最佳答案
映射您的用例
我的回答是基于从您的一个相关问题中收集到的信息:
由于您映射的类没有源代码(因此无法添加 JAXB 注释),因此我建议使用 @XmlElements
映射。
@XmlElements({
@XmlElement(name="Button", type=Button.class),
@XmlElement(name="Combo", type=Combo.class)
})
public List<Widget> getWidgets() {
return widgets;
}
@XmlElements
对应xsd:choice
的XML Schema概念。
关于@XmlRootElement
Ok, I am missing quite a lot of things out here. It seems like I add to add this @XmlRootElement annotation to my subclasses of Button and Combo to achieve that.
Can anyone explain to me why I need that annotation in my subclasses... I am confused, I thought an XML would only have a @XmlRootElement which in my case should be in MainGroup class.
@XmlRootElement
对应于 XML 模式中的全局元素,它涉及的不仅仅是您正在解码的文档中的根元素。我将在下面描述几个角色:
@XmlElementRef
@XmlElementRef
对应置换组的概念。在 XML 模式中,您可以指定一个全局元素可以替换另一个。在 JAXB 中,@XmlRootElement
(和 @XmlElementDecl
)用于指定全局元素:
@XmlAnyElement
@XmlAnyElement
对应XML Schena中xs:any的概念。这是文档的一部分,格式非常自由。在 JAXB 中,当您使用 @XmlAnyElement(lax=true)
映射属性时,它会将匹配 @XmlRootElement
声明的元素转换为相应的域对象。
关于java - 使用 @XmlAnyElement 的 XML 映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11661769/