2
votes

Given the following XML structure:

<root>
  <data>x</data>
  <details>
    <some_other_element>...</some_other_element>
    <collection>
      <element><a>1</a></element>
      <element><a>2</a></element>
      <element><a>3</a></element>
    <collection>
  </details>
</root>

How would I unmarshal this into a mostly flat POJO using MOXy? I tried this approach (getters and setters left out for brevity):

@XmlRootElement(name = "root")
class Root {
  @XmlElement
  private String data;

  @XmlElement
  @XmlPath("details/some_other_element")
  private String someOtherElement;

  @XmlPath("details")
  @XmlElementWrapper(name = "collection")
  @XmlElement(name = "element")
  private Collection<Element> elements;
}

class Element {
  @XmlElement
  private String a;
}

Unfortunately, this just adds a single uninitialized to the elements collection. I'd like to avoid having to declare a Details class (which does indeed work) as that breaks the other @XmlPath mappings for elements below <details>.

I have verified that MOXy is actually loaded (as declared in the jaxb.properties).

Any ideas?

1

1 Answers

3
votes

Try adding the wrapping tag and the element to the @XmlPath instead of using @XmlElementWrapper:

@XmlPath("details/collection/element")
@XmlElement(name = "element")
private Collection<Element> elements;

I think you can even keep the @XmlElementWrapper annotation in case of future change of the jaxb provider.


Below is the minimal annotations your require for your use case:

package forum11153599;

import java.util.Collection;
import javax.xml.bind.annotation.*;
import org.eclipse.persistence.oxm.annotations.XmlPath;

@XmlRootElement
class Root {
    @XmlElement
    private String data;

    @XmlPath("details/some_other_element/text()")
    private String someOtherElement;

    @XmlPath("details/collection/element")
    private Collection<Element> elements;

}