I'd like to unmarshall a xml file with nested children with same name to a single class. I tried everything I found but nothing work, the values of nested children remain null.
What is wrong ?
jaxb.properties
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
myFile.xml
<?xml version="1.0" encoding="UTF-8"?>
<clock>
<name>myClock</name>
<times>
<starttime>09:00</starttime>
<endtime>12:00</endtime>
<starttime>13:00</starttime>
<endtime>17:00</endtime>
</times>
</clock>
Clock.java
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Clock {
@XmlElement
private String name;
@XmlPath("times/starttime[1]/text()")
private String amStartTime;
@XmlPath("times/endtime[1]/text()")
private String amEndTime;
@XmlPath("times/starttime[2]/text()")
private String pmStartTime;
@XmlPath("times/endtime[2]/text()")
private String pmEndTime;
}
Test code
File file = new File("myFile.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Clock.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Clock clock = (Clock) jaxbUnmarshaller.unmarshal(file);
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(clock, System.out);
Ouput
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<clock>
<name>myClock</name>
</clock>
2 solutions found here : JAXBContext, jaxb.properties and moxy
I can either put the jaxb.properties in the package of Clock.java or get my JABXContext instance this way :
JAXBContext jaxbContext = JAXBContextFactory.createContext(new Class[] {Clock.class}, null);