2

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>
4
  • What do you get if you fully populate your object model and marshal it? Also if you call .getClass() on your jaxbContext what do you see as the real class?
    – bdoughan
    Jul 10, 2014 at 20:02
  • <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <clock> ` <name>myClock</name>` ` <amStartTime>1:00</amStartTime>` ` <amEndTime>2:00</amEndTime>` ` <pmStartTime>3:00</pmStartTime>` ` <pmEndTime>4:00</pmEndTime>` </clock> and class com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl
    – elfdev
    Jul 10, 2014 at 20:39
  • 1
    I finally found where was my mistake. My jaxb.properties was not read because it wasn't in the package of my domain class. Now it works perfectly !
    – elfdev
    Jul 10, 2014 at 21:08
  • Can you add that as an answer? This will help people in the future who encounter this in the future and find your question.
    – bdoughan
    Jul 10, 2014 at 21:12

1 Answer 1

1

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);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.