Mansour
Mansour

Reputation: 687

JAXB binding nested elements

I am using JAXB-impl. I need to be able to map nested elements to class fields as simple types. For example:

<mapping>

    <search>
        <channel>main-channel</channel>
        <url>my-channel-url</url>
    </search>

    <items>
        <item>first</item>
        <item>second</item>
        <item>third</item>
    </items>

</mapping>

Assuming I need to bind "url" tag to a field in the class, this will not work (of course):

class Mapping{

    @XmlElement
    private String url;
}

@XmlElementWrapper, is for collections only. I have seen some post about using eclipse MOXy, and utilize @XmlPath, but this is not an option. It has to be JAXB-impl.

for reference: http://wiki.eclipse.org/EclipseLink/Examples/MOXy/XPath#Marshal_to_XML_-_MOXy_Customization_.231_-_Grouping_Element

Is there a way to get this mapping without having to create these extra nested classes ?

Upvotes: 2

Views: 2102

Answers (1)

Ilya
Ilya

Reputation: 29673

With additional class Search, but this class is private nested class, and not used outside of Mapping class.
public API of class Mapping returns url as expected

@XmlAccessorType(XmlAccessType.FIELD)
class Mapping
{
   @XmlAccessorType(XmlAccessType.FIELD)
   private static class Search
   {
      private String channel;
      private String url;
   }

   private Search search;

   public String getUrl()
   {
      return search == null ? null : search.url;
   }
}

Upvotes: 5

Related Questions