JAXB unmarshal picks root name at runtime

I have several xml files with alternate root elements:

<ulti86>, 
<ulti75>, 
<ulti99>....

      

Otherwise, the xml structure will be the same.

I want to unmount these files in the same pojo.

I have seen that it is possible to change the name of an element in the sorting process at runtime with

JAXBElement and Qname (like : JAXBElement<Customer> jaxbElement = 
new JAXBElement<Customer>(new QName(null, "customer"), Customer.class, customer);)

      

Can I specify 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);

      

+3


source to share


2 answers


You can use one of the methods unmarshal

on Unmarshaller

that takes a parameter Class

to get the behavior you are looking for. Telling JAXB what type Class

you are picky about it doesn't need to compute it by the root element itself.

StreamSource xmlSource = new StreamSource(getFullFileName());
JAXBElement<Ulti> jaxbElement = unmarshaller.unmarshal(xmlSource, Ulti.class);
Ulti icc = jaxbElement.getValue();

      



Note:

The benefit of using Unmarshaller.unmarshal(Source, Class)

over JAXB.unmarshal(File, Class)

is the performance benefit of processing metadata only once, creating JAXBContext

that can be reused.

+2


source


Using a class JAXB

, the name of the root element should be out of date, you can change it and still unmarshal will succeed.

Example xml input:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<point>
    <x>1</x>
    <y>2</y>
</point>

      



Cancel Print 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 will get the same result without any errors.

+2


source







All Articles