I have XML structure.
<cars>
<car name = "BMW" engine="2.5"/>
<car name = "Lexus" engine="4.5"/>
<car name = "VW" engine="1.4"/>
<car name = "Honda" engine="2.0"/>
</cars>
I have Java classes for each of car model.
public class BMW extends Car{
public BMW(){
}
}
How do I design my main() class to parse this XML and atomatically invoke constructor for required Car. Lets say I get a node <.car name = “BMW” engine=”2.5″/> this means I want to invoke BMW constructor create a BMW object and store everything into List<.Car>.
Thanks for any tips! 🙂
You could map this use case using any JAXB (JSR-222) by taking advantage of an
XmlAdapter:CarAdapter
In your example you are using a custom node as the inheritance indicator. Using the standard JAXB APIs we can use an
XmlAdapterto map this use case. AnXmlAdapterconverts from a domain object to an object that is easier for the JAXB implementation (Metro, MOXy, JaxMe, etc) to map.Car
The
@XmlJavaTypeAdapterannotation is used to associate theXmlAdapterwith theCarclass:BMW
Below is an example of one of the subclasses.
Cars
We need an
Objectto represent the root node in our tree. We will define theCarsclass to serve this role:Demo
Output
For More Information