【问题标题】:JAXB inheritance + element renameJAXB 继承 + 元素重命名
【发布时间】:2012-07-05 08:13:54
【问题描述】:

我有以下结构:

@XMLTransient
public abstract class Foo {
   protected String name;
}

@XmlRootElement
@XmlType(propOrder={"name"})
public class BarX extends Foo {

   public String getXThing() {
      return name;
   }

   public void setXThing(String thing) {
      name = thing;
   }
}

@XmlRootElement
@XmlType(propOrder={"name"})
public class BarY extends Foo {

   public String getYBlah() {
      return name;
   }

   public void setYBlah(String blah) {
      name = blah;
   }
}

在 XML 中,我需要 BarX 而不是 name 标签 thing,而对于 BarY,我希望使用 blah 而不是 name。有可能吗?我怎样才能得到这个?

【问题讨论】:

    标签: java xml inheritance jaxb


    【解决方案1】:

    您可以执行以下操作(您已经非常接近了):

    Foo

    package forum11340316;
    
    import javax.xml.bind.annotation.XmlTransient;
    
    @XmlTransient
    public abstract class Foo {
       protected String name;
    }
    

    BarX

    package forum11340316;
    
    import javax.xml.bind.annotation.*;
    
    @XmlRootElement
    @XmlType(propOrder={"XThing"})
    public class BarX extends Foo {
    
       @XmlElement(name="thing")
       public String getXThing() {
          return name;
       }
    
       public void setXThing(String thing) {
          name = thing;
       }
    
    }
    

    BarY

    package forum11340316;
    
    import javax.xml.bind.annotation.*;
    
    @XmlRootElement
    @XmlType(propOrder={"YBlah"})
    public class BarY extends Foo {
    
       @XmlElement(name="blah")
       public String getYBlah() {
          return name;
       }
    
       public void setYBlah(String blah) {
          name = blah;
       }
    
    }
    

    演示

    package forum11340316;
    
    import javax.xml.bind.*;
    
    public class Demo {
    
        public static void main(String[] args) throws Exception {
            JAXBContext jc = JAXBContext.newInstance(BarX.class, BarY.class);
            Marshaller marshaller = jc.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    
            BarX barX = new BarX();
            barX.setXThing("XThing");
            marshaller.marshal(barX, System.out);
    
            BarY barY = new BarY();
            barY.setYBlah("YBlah");
            marshaller.marshal(barY, System.out);
        }
    
    }
    

    输出

    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <barX>
        <thing>XThing</thing>
    </barX>
    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <barY>
        <blah>YBlah</blah>
    </barY>
    

    更多信息

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-04
      • 1970-01-01
      • 1970-01-01
      • 2017-02-06
      • 2017-07-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多