JAXB-具有多个名称和类型的XmlElement [英] JAXB - XmlElement with multiple names and types
问题描述
我具有以下类层次结构:
I have the following class hierarchy:
@XmlRootElement
public abstract class Animal{}
@XmlRootElement
public class Dog extends Animal{}
@XmlRootElement
public class Cat extends Animal{}
@XmlRootElement
public class Lion extends Animal{}
和一个具有名为animal的属性的类:
and a class which has an attribute named animal:
@XmlRootElement
public class Owner{
private Animal animal;
}
我想允许以下不同的XML模式,并将模式中的Animal Type绑定到Owner class
I would like to allow different XML Schemas as follows and bind the Animal Type in the schema to animal object
in Owner class
<Owner>
<Dog></Dog>
</Owner>
<Owner>
<Cat></Cat>
</Owner>
<Owner>
<Lion></Lion>
</Owner>
我发现的解决方案使用XmlElements
,它可以采用多个XmlElement
字段并创建一个集合.但是,就我而言,我不需要一个集合,而只需一个属性.
The solutions that I have found use XmlElements
which can take multiple XmlElement
fields and creates a collection. However, in my case I don't need a collection but a single attribute.
JAXB是否为此问题允许任何XmlElement多重命名约定? 还有其他注释可以解决此问题吗?
Does JAXB allow any XmlElement multiple naming convention for this problem? Is there any other annotation which could solve this problem?
注意:我已经在stackoverflow及其周围查看了多个类似问题的答案,但几乎所有答案都创建了一个集合,而不是一个对象.我找到的最接近的答案是: @具有多个名称的XmlElement
Note: I have looked at multiple answers to similar questions in stackoverflow and around but almost all of them create a collection instead of a single object. The closest answer I have found is this : @XmlElement with multiple names
我认为此解决方案可能会起作用.必须进行测试
Edit : I think this solution might work. Have to test it out
推荐答案
I got it to work using the @XmlElements
annotation, as follows:
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElements;
import javax.xml.bind.annotation.XmlRootElement;
import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
public class Main {
public static void main(String[] args) throws JAXBException {
String xml = "<owner><dog></dog></owner>";
JAXBContext jaxbContext = JAXBContext.newInstance(Owner.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Owner owner = (Owner) jaxbUnmarshaller.unmarshal(
new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8)));
System.out.println(owner.getAnimal().getClass());
}
}
abstract class Animal {}
class Dog extends Animal {}
class Cat extends Animal {}
class Lion extends Animal {}
@XmlRootElement
class Owner {
@XmlElements({
@XmlElement(name = "dog", type = Dog.class),
@XmlElement(name = "cat", type = Cat.class),
@XmlElement(name = "lion", type = Lion.class)
})
private Animal animal;
public Animal getAnimal() {
return animal;
}
}
使用Oracle Java 8 SDK附带的默认JAXB实现,输出如下:
Using the default JAXB implementation that ships with the Oracle Java 8 SDK, this prints out:
class Dog
这篇关于JAXB-具有多个名称和类型的XmlElement的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!