JAXB通过映射

时间:2012-06-05 20:55:46

标签: java xml jaxb

鉴于以下类别:

@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;
   }

}

我需要添加什么注释(注释的位置)才能获得以下xml:

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

我只是将具体的例子放在了我的头顶,因此标签出现在它可能没有意义的地方。但我真正想知道的是如何对Child类进行传递。基本上它很容易做以下的映射(我不想要):

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

1 个答案:

答案 0 :(得分:0)

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;
}

打印

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<parent>
    <age>55</age>
</parent>