2012-07-05 3 views
2

J'ai la construction suivante:héritage JAXB + élément renomment

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

Dans le XML j'ai besoin pour BarX au lieu de name l'étiquette thing et Bary Je voudrais avoir blah au lieu de name. Est-ce possible et comment je peux l'obtenir?

Répondre

1

Vous pouvez effectuer les opérations suivantes (vous étiez déjà assez proche):

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

} 

Démo

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

} 

Sortie

<?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> 

Pour plus d'informations

+1

Aaah, ok. Merci beaucoup. – arothe

Questions connexes