Note: I'm the EclipseLink JAXB (MOXy) lead and a member of the JAXB 2 (JSR-222) expert group.
Assuming your XML document looks something like the following:
<?xml version="1.0" encoding="UTF-8"?>
<rows>
<row>
<col1>a1</col1>
<col2>b1</col2>
<col3>c1</col3>
</row>
<row>
<col1>a1</col1>
<col2>b2</col2>
<col3>c2</col3>
</row>
</rows>
You could leverage MOXy's @XmlPath annotation and do something like. EclipseLink also includes a JPA implementation:
Rows
You will need to create a Root object to hold everything:
package forum8577359;
import java.util.List;
import javax.xml.bind.annotation.*;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Rows {
@XmlElement(name="row")
private List<A> rows;
}
A
Since the contents for the A
, B
, and C
objects are all at the same level you can use MOXy's @XmlPath
annotation and specify the "."
XPath. This tells MOXy that the object, and the object it is referencing occur at the same level:
package forum8577359;
import javax.xml.bind.annotation.*;
import org.eclipse.persistence.oxm.annotations.XmlPath;
@XmlAccessorType(XmlAccessType.FIELD)
public class A {
private String col1;
@XmlPath(".")
private B b;
}
B
Again we use @XmlPath(".")
to map the relationship between B
and C
:
package forum8577359;
import javax.xml.bind.annotation.*;
import org.eclipse.persistence.oxm.annotations.XmlPath;
@XmlAccessorType(XmlAccessType.FIELD)
public class B {
private String col2;
@XmlPath(".")
private C c;
}
C
package forum8577359;
import javax.xml.bind.annotation.*;
@XmlAccessorType(XmlAccessType.FIELD)
public class C {
private String col3;
}
Demo
The following demo code can be used to run this example:
package forum8577359;
import java.io.File;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Rows.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("src/forum8577359/input.xml");
Rows rows = (Rows) unmarshaller.unmarshal(xml);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(rows, System.out);
}
}
jaxb.properties
To specify MOXy as your JAXB provider you need to include a jaxb.properties
file in the same package as your domain classes with the following entry:
javax.xml.bind.context.factory = org.eclipse.persistence.jaxb.JAXBContextFactory
For More Information