Reputation: 323
I have several xml files with alternative root elements :
<ulti86>,
<ulti75>,
<ulti99>....
Otherwise,the xml structure is the same.
I want to unmarshal these files in the same pojo.
I saw is possible to change the name of an element in marshalling opération at runtime with
JAXBElement and Qname (like : JAXBElement<Customer> jaxbElement =
new JAXBElement<Customer>(new QName(null, "customer"), Customer.class, customer);)
is it possible to indicate the name of the root element at runtime in unmarshalling ?
Ulti class :
@XmlRootElement
public class Ulti {
....
}
unmarshal method :
JAXBContext jaxbContext = JAXBContext.newInstance(Ulti.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
File xmlFile = new File(getFullFileName());
Ulti icc = (Ulti) unmarshaller.unmarshal(xmlFile);
Upvotes: 4
Views: 3160
Reputation: 148987
You can use one of the unmarshal
methods on Unmarshaller
that take a Class
parameter to get the behaviour you are looking for. By telling JAXB what type of Class
you are unmarshalling it doesn't need to figure one out itself by the root element.
StreamSource xmlSource = new StreamSource(getFullFileName());
JAXBElement<Ulti> jaxbElement = unmarshaller.unmarshal(xmlSource, Ulti.class);
Ulti icc = jaxbElement.getValue();
Note:
The advantage of using Unmarshaller.unmarshal(Source, Class)
over JAXB.unmarshal(File, Class)
is the performance benefit of processing the metadata only once by creating a JAXBContext
that can be reused.
Upvotes: 2
Reputation: 417582
Using the JAXB
class the name of the root element should be irrelevant, you can change it and still unmarshal will succeed.
Example input xml:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<point>
<x>1</x>
<y>2</y>
</point>
Unmarshaling code:
Point p = JAXB.unmarshal(new File("p.xml"), Point.class);
System.out.println(p); // Output: java.awt.Point[x=1,y=2]
Now if you change the root element to for example "<p2oint>"
and run it again, you get the same result without any errors.
Upvotes: 3