简体   繁体   English

JAXB直通映射

[英]JAXB Pass through mapping

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: 我需要添加什么注释(注释在何处)才能获得以下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. 但是我真正想知道的是如何传递给Child类。 Essentially its easy to do the mapping for the following (which I DON'T want): 从本质上讲,它很容易为以下内容进行映射(我不想要):

<parent>
  <child>
    <age>55</age> 
  </child>  
</parent>
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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM