Tiny
Tiny

Reputation: 27899

Is it possible to get XML elements based on some attribute value/s using JAXB?

I have created an XML file using JAXB named Height.xml. The structure looks like the following.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<heightList>
    <measurement id="5">
        <height>4'4"</height>
    </measurement>
    <measurement id="4">
        <height>4'3"</height>
    </measurement>
    <measurement id="3">
        <height>4'2"</height>
    </measurement>
    <measurement id="2">
        <height>4'1"</height>
    </measurement>
    <measurement id="1">
        <height>4'0"</height>
    </measurement>
</heightList>

This XML file can be unmarshalled to a List<Height> as follows.

JAXBContext jaxb=JAXBContext.newInstance(HeightList.class);
File file=new File("Height.xml");
List<Height> heightList = ((HeightList) jaxb.createUnmarshaller().unmarshal(file)).getList();

Is it possible to get an XML element based on its attribute id so that instead of List<Height>, only one object of type Height is fetched? The id attribute is unique.


The associated classes:

Height:

public final class Height implements Serializable
{
    private Integer id;
    private String height;
    private static final long serialVersionUID = 1L;

    public Height() {}

    @XmlAttribute(name = "id")
    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getHeight() {
        return height;
    }

    public void setHeight(String height) {
        this.height = height;
    }
}

HeightList:

@XmlRootElement(name = "heightList")
@XmlAccessorType(XmlAccessType.PROPERTY)
public final class HeightList implements Serializable
{
    @XmlElement(name="measurement")
    private List<Height>list;
    private static final long serialVersionUID = 1L;

    public HeightList() {}

    public HeightList(List<Height> list) {
        this.list = list;
    }

    public List<Height> getList() {
        return list;
    }
}

Upvotes: 0

Views: 781

Answers (1)

laune
laune

Reputation: 31290

You have a List heightList, which you retrieve from the document/object tree without any additional overhead - it is part of that tree. Partial unmarshalling isn't done.

To locate the Height with a specific ID value:

Height getById( List<Height> list, Integer id ){
    for( Height h: list ){
        if( h.getId().equals(id) ) return h;
    }
    return null;
}

It might be worth considering something like XSLT to reduce the XML document to one containing a single <mesurement> and unmarshal that.

Probably not worth the effort unless the list is very long.

Upvotes: 1

Related Questions