title: JAXB2: Mapping nested elements into the same Java class
body: <p>I'm having trouble trying to map nested elements into the same Java class.</p>
  
  <p><strong>XML</strong></p>
  
  <p>What I'm trying to do here is to set <code>id</code> attribute and <code>text</code> element into <code>SlideText</code> class.</p>
  
  <pre><code>&lt;module name="test project"&gt;
      &lt;slide id="1"&gt;
          &lt;layout&gt;
              &lt;text&gt;hello&lt;/text&gt;
          &lt;/layout&gt;
      &lt;/slide&gt;
  &lt;/module&gt;
  </code></pre>
  
  <p><strong>Module class</strong></p>
  
  <pre><code>@XmlRootElement
  @XmlAccessorType(XmlAccessType.FIELD)
  public class Module {
      @XmlAttribute
      private String  name;
  
      @XmlElements({
          @XmlElement(name = "slide", type = SlideText.class)
      })
      private Slide   slide;
  }
  </code></pre>
  
  <p><strong>Slide class</strong></p>
  
  <pre><code>@XmlRootElement
  @XmlAccessorType(XmlAccessType.FIELD)
  public abstract class Slide {
      @XmlAttribute
      private String  id;
  }
  </code></pre>
  
  <p><strong>SlideText class</strong></p>
  
  <p>I tried using <code>@XmlElementWrapper</code> on <code>text</code> property, but I get an exception that <code>@XmlElementWrapper</code> can only be applied to a collection.</p>
  
  <pre><code>@XmlRootElement
  @XmlAccessorType(XmlAccessType.FIELD)
  public class SlideText extends Slide {
  
      // how to map this to layout/text elements?
      private String  text;
  }
  </code></pre>
  
  <p>Is there a way to map <code>&lt;layout&gt;&lt;text&gt;hello&lt;/text&gt;&lt;/layout&gt;</code> into <code>SlideText</code>'s <code>text</code> property?</p>
  
  <p>Thanks.</p>
  
  <p><strong>UPDATE</strong></p>
  
  <p>To illustrate what I'm trying to accomplish here, the slide can be of any type depending on what layout is used. A <code>module</code> knows it's a <code>slide</code> but it doesn't know what slide it is, which is why I have the abstract <code>Slide</code> class.</p>
  
  <p>Essentially, if this works, I'll be creating <code>SlideImage</code> and <code>SlideTextVideo</code> that extends <code>Slide</code>.</p>
  
  <p>Here's how the actual XML file looks like:-</p>
  
  <pre><code>&lt;module name="test project"&gt;
      &lt;slide id="1"&gt;
          &lt;layout-text&gt;
              &lt;text&gt;hello&lt;/text&gt;
          &lt;/layout-text&gt;
      &lt;/slide&gt;
  &lt;/module&gt;
  &lt;module name="test project"&gt;
      &lt;slide id="2"&gt;
          &lt;layout-image&gt;
              &lt;image-path&gt;img.jpg&lt;/image-path&gt;
          &lt;/layout-image&gt;
      &lt;/slide&gt;
  &lt;/module&gt;
  &lt;module name="test project"&gt;
      &lt;slide id="3"&gt;
          &lt;layout-text-video&gt;
              &lt;text&gt;hello&lt;/text&gt;
              &lt;video-path&gt;a.mp4&lt;/video-path&gt;
          &lt;/layout-text-video&gt;
      &lt;/slide&gt;
  &lt;/module&gt;
  </code></pre>