Unmarshal List to Types

浪子不回头ぞ 提交于 2019-12-11 11:52:20

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/44590229/unmarshal-list-to-types

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!