Java spring XML binding based on conditions using

2019-07-29 06:44发布

问题:

I am binding XML to object using JAXB, is it possible to bind based on conditions such as

Bind href attribute in api:page element where attribute position is equal to next.

Or get all records as standard list and then filter out by using if condition

<api:pagination results-count="93" items-per-page="25">
  <api:page position="this" href="https://url1.com" />
  <api:page position="next" href="https://url1.com?pid=2" />
</api:pagination>

回答1:

It is not necessary to make a transformation for such a simple setup.Take advantage of @XmlAnyElement https://docs.oracle.com/javase/8/docs/api/javax/xml/bind/annotation/XmlAnyElement.html and just map your collection as a list of Elements.

@XmlElementWrapper(name = "pagination")
@XmlAnyElement
public List<Element> getPages() {
        return pages;
 }

Where Element is org.w3c.dom.Element

The @XmlElementWrapper is optional, if you want you can map your pagination element. I am not sure you need it though.

Then you extract the position with:

page.getAttribute("position")

and

page.getAttribute("href") 

for the url