Search code examples
javajaxbjaxb2

Unmarshal List to Types


I have this xml

<data-set>
    <list-property name="columns">...</list-property>
    <list-property name="resultSet">...</list-property>
<data-set>

Need to unmarshal this to object:

public class DataSet {

    private Columns columns;

    private ResultSet resultSet;
    ...
}

Help me to implement that if it possible.

Update What I tried to do:

public class DataSet {

    @XmlElement("list-property")
    @XmlJavaTypeAdapter(DataSetListPropertyAdapter.class)
    private Columns columns;

    @XmlElement("list-property")
    @XmlJavaTypeAdapter(DataSetListPropertyAdapter.class)
    private ResultSet resultSet;

    ...
}

public class DataSetListPropertyAdapter extends XmlAdapter<ListProperty, ListProperty> {
@Override
public ListProperty unmarshal(ListProperty v) throws Exception {
    ListProperty listProperty;
    switch (v.getName()) {
        case "columns":
            listProperty = new Columns();
            break;
        case "resultSet":
            listProperty = new ResultSet();
            break;
        default:
            listProperty = new ListProperty();
    }
    listProperty.setStructure(v.getStructure());
    return listProperty;
}

    @Override
    public ListProperty marshal(ListProperty v) throws Exception {
        return v;
    }
}

public class Columns extends ListProperty {
public Columns() {
    name = "columns";
}
}

public class ListProperty extends NamedElement implements PropertyType{

@XmlElement(name = "structure")
private List<Structure> structure = new ArrayList<>();
}

@XmlTransient
public class NamedElement {

@XmlAttribute(name = "name", required = true)
protected String name;
}

When go unmarshalling then only first element of annotated objects parsed. Another is null. When I comment first then second becames parsed.


Solution

  • I do not think what you're trying to do is possible with JAXB reference implementation.

    However, if you can change implementation, EclipseLink MOXy offer the @XmlPath that should resolve your problem :

    public class DataSet {
    
        @XmlPath("node[@name='columns']")
        @XmlJavaTypeAdapter(DataSetListPropertyAdapter.class)
        private Columns columns;
    
        @XmlPath("node[@name='resultSet']")
        @XmlJavaTypeAdapter(DataSetListPropertyAdapter.class)
        private ResultSet resultSet;
    
        ...
    }
    

    More on @XmlPath : http://www.eclipse.org/eclipselink/documentation/2.4/moxy/advanced_concepts005.htm