我java jaxb2.0
用来做xml marshalling
和unmarshalling
。
我遇到了这样的问题。
示例 xml 是这样的* (fruit.xml) *:
<fruitPacks>
<fruit name="apple1" type="apple" isApple="true"/>
<fruit name="banana1" type="banana" isBanana="true"/>
<fruit name="apple2" type="apple" isApple="true"/>
</fruitPacks>
和这样的java类:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "fruitPacks")
@XmlRootElement
public class FruitPacks
{
@XmlElement(name = "fruit")
private List<Fruit> fruits
}
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "fruit")
@XmlSeeAlso({ Apple.class, Banana.class })
public class Fruit{
@XmlAttribute
private String name;
@XmlAttribute
private String type;
}
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "apple")
public class Apple extends Fruit{
@XmlAttribute
private boolean isApple = true;
}
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "banana")
public class Banana extends Fruit{
@XmlAttribute
private boolean isBanana = true;
}
和解组代码是:
public class JAXBTest {
public static void main(String [] args) throws Exception{
JAXBContext jc = JAXBContext.newInstance(FruitPacks.class,Fruit.class,Apple.class, Banana.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
Object obj = unmarshaller.unmarshal(new File("fruit.xml"));
System.out.println(obj);
}
}
所以我想要做的是:
在解组xml时,水果的构造将根据类型属性自动完成到子类(Apple,Banana)。
我该怎么做?