3

给定以下类:

@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>
4

1 回答 1

1
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>
于 2012-07-01T05:47:18.450 回答