You can use a combination of @XmlElementRef and JAXBElement to create dynamic element names.
The idea is this:
- Make
Characteristica subclass JAXBElementand override the method getName()to return the name of the properties of the basis Characteristic. - Annotate
characteristicswith @XmlElementRef. - Provide
@XmlRegistry( ObjectFactory) @XmlElementDecl(name = "characteristic").
.
( ):
@Test
public void marshallsDynamicElementName() throws JAXBException {
JAXBContext context = JAXBContext.newInstance(ObjectFactory.class);
final Characteristics characteristics = new Characteristics();
final Characteristic characteristic = new Characteristic(
"store_capacity", "40");
characteristics.getCharacteristics().add(characteristic);
context.createMarshaller().marshal(characteristics, System.out);
}
:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<characteristics><store_capacity>40</store_capacity></characteristics>
characteristics. characteristics, @XmlElementRef. , JAXBElement, @XmlRootElement - .
@XmlRootElement(name = "characteristics")
public class Characteristics {
private final List<Characteristic> characteristics = new LinkedList<Characteristic>();
@XmlElementRef(name = "characteristic")
public List<Characteristic> getCharacteristics() {
return characteristics;
}
}
ObjectFactory - @XmlRegistry @XmlElementDecl:
@XmlRegistry
public class ObjectFactory {
@XmlElementDecl(name = "characteristic")
public JAXBElement<String> createCharacteristic(String value) {
return new Characteristic(value);
}
}
, characteristics @XmlRootElement - , JAXBElement s. @XmlRootElement , . JAXBElement . JAXBElement getName():
public class Characteristic extends JAXBElement<String> {
private static final long serialVersionUID = 1L;
public static final QName NAME = new QName("characteristic");
public Characteristic(String value) {
super(NAME, String.class, value);
}
public Characteristic(String characteristic, String value) {
super(NAME, String.class, value);
this.characteristic = characteristic;
}
@Override
public QName getName() {
final String characteristic = getCharacteristic();
if (characteristic != null) {
return new QName(characteristic);
}
return super.getName();
}
private String characteristic;
@XmlTransient
public String getCharacteristic() {
return characteristic;
}
public void setCharacteristic(String characteristic) {
this.characteristic = characteristic;
}
}
getName() . Characteristic, , Characteristic .
GitHub.