2012-07-05 167 views
2

我有以下結構:JAXB繼承+元素命名

@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和巴里我想有blah,而不是name。這是可能的嗎?我怎麼能得到這個?

回答

1

你可以做以下的(你已經非常接近):

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

} 

巴里

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> 

更多信息

+1

Aaah,好的。非常感謝。 – arothe