Question

Let's say there is a class named

// with respect.
public class BlaiseDoughan {
}

I know I can change the element's name like this.

@XmlRootElement
public class MyRoot {

    @XmlElement(name = "blaise-doughan") // I want this
    private BlaiseDoughan blaiseDoughan
}

Is there any way to permanently set the target element name of BlaiseDoughan to blaise-doughan in every or any occurrence without name attribute?

I mean

@XmlRootElement
public class SomeOtherRoot {

    @XmlElement // without the [name = "blaise-doughan"] part?
    private BlaiseDoughan blaiseDoughan
}

Is there any package-level technique for this?

Was it helpful?

Solution

You could do:

Java Model

BlaiseDoughan

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name="blaise-doughan")
public class BlaiseDoughan {

}

MyRoot

And then every reference to it could be mapped with @XmlElementRef.

import javax.xml.bind.annotation.*;

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class MyRoot {

    @XmlElementRef
    private BlaiseDoughan blaiseDoughan;

    public void setBlaiseDoughan(BlaiseDoughan blaiseDoughan) {
        this.blaiseDoughan = blaiseDoughan;
    }

}

Demo Code

Demo

import javax.xml.bind.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(MyRoot.class);

        MyRoot myRoot = new MyRoot();
        myRoot.setBlaiseDoughan(new BlaiseDoughan());

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(myRoot, System.out);
    }

}

Output

<?xml version="1.0" encoding="UTF-8"?>
<myRoot>
    <blaise-doughan/>
</myRoot>

Why This Works

@XmlElementRef corresponds to using ref in the element definition:

<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
   <xsd:complexType name="blaiseDoughan"/>
   <xsd:complexType name="myRoot">
      <xsd:sequence>
         <xsd:element ref="blaise-doughan"/>
      </xsd:sequence>
   </xsd:complexType>
   <xsd:element name="myRoot" type="myRoot"/>
   <xsd:element name="blaise-doughan" type="blaiseDoughan"/>
</xsd:schema>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top