2

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 Answer 1

3

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;

}
2
  • +1 - I'm the MOXy lead and your answer is correct. I hope you don't mind I added an example of what the Root class could look like.
    – bdoughan
    Jun 22, 2012 at 10:00
  • 1
    Excellent, works like a charm (although I am quite certain that I also tried this variant before ;-) )! Jun 22, 2012 at 10:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.