Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAXB Pass through mapping

Tags:

java

xml

jaxb

Given the following classes:

@XmlRootElement(name = "parent")
class Parent {
   private Child child;

   // What annotation goes here
   public Child getChild() {
     return child;
   }

   public void setChild(Child child) {
     this.child = child;
   }
}

class Child {
   private Integer age;

   @XmlElement(name = "age")
   public Integer getAge() {
     return age;
   }

   public void setAge(Integer Age) {
     this.age = age;
   }

}

What annotation do I need to add (where the comment is) to get the following xml:

<parent>
  <age>55</age> 
</parent>

I just made the specific example off the top of my head so having the tag appear where it is probably doesn't make sense. But what I really want to know is how to do a pass-through to the Child class. Essentially its easy to do the mapping for the following (which I DON'T want):

<parent>
  <child>
    <age>55</age> 
  </child>  
</parent>
like image 226
akdik Avatar asked Jun 11 '26 23:06

akdik


1 Answers

import javax.xml.bind.*;
import javax.xml.bind.annotation.*;

@XmlRootElement
class Parent {

    public static void main(String[] args) throws JAXBException {

        final Child child = new Child();
        child.age = 55;

        final Parent parent = new Parent();
        parent.child = child;

        final JAXBContext context = JAXBContext.newInstance(Parent.class);
        final Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,
                               Boolean.TRUE);
        marshaller.marshal(parent, System.out);
        System.out.flush();
    }

    @XmlElement
    public Integer getAge() {
        return child == null ? null : child.age;
    }

    @XmlTransient
    private Child child;
}

class Child {

    @XmlElement
    protected Integer age;
}

prints

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<parent>
    <age>55</age>
</parent>
like image 172
Jin Kwon Avatar answered Jun 13 '26 11:06

Jin Kwon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!