how can i construct the xml element based on the type attribute when using jaxb2?

Plotoully

New Member
I'm using \[code\]java jaxb2.0\[/code\] to do \[code\]xml marshalling\[/code\] and \[code\]unmarshalling\[/code\].
I encountered a problem like this.
the sample xml is like this*(fruit.xml)*:\[code\]<fruitPacks> <fruit name="apple1" type="apple" isApple="true"/> <fruit name="banana1" type="banana" isBanana="true"/> <fruit name="apple2" type="apple" isApple="true"/></fruitPacks>\[/code\]and java class like this:\[code\]@XmlAccessorType(XmlAccessType.FIELD)@XmlType(name = "fruitPacks")@XmlRootElementpublic 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;}\[/code\]and unmarshal code is :\[code\]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);} }\[/code\]So what I want to do is:
when unmarshalling the xml, the construction of the fruit will automatically done to the subclasses (Apple, Banana) based on the type attribute.
How can i do it?
 
Back
Top