Wednesday, 25 February 2015

JAXB how to pass namespace prefix to child nodes of type which is used multiple times



What I am trying to achieve is to reuse Type class and write it's fields with different namespace prefixes. Namespaces are set to list of academicTitle and otherTitle in Person class, but this namespaces are not passed to Type attributes, they are not getting applied. The solution I came up with so far is to add @XmlType(namespace='...') annotation to Type class, but than it's tied with this single namespace. I would like to be able to use different namespaces for this common class, and at the same time I do not want to extend Type classes N times to only override @XmlType(namespace='...') annotation in order to provide it's own namespace


XML generated with JAXB



<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns3:person xmlns:ns3="http://ift.tt/1EQA90k"
xmlns:bar="http://ift.tt/1ajV8z9">
<id>44645547657</id>
<bar:academicTitles>
<bar:academicTitle>
<bar:value>15</bar:value>
<bar:text>Mag.</bar:text>
</bar:academicTitle>
<bar:academicTitle>
<bar:value>15</bar:value>
<bar:text>Mag.</bar:text>
</bar:academicTitle>
</bar:academicTitles>
<otherTitles>
<value>17</value>
<text>Other title</text>
</otherTitles>
</ns3:person>


Person.java



@XmlRootElement(name = "person", namespace = "http://ift.tt/1EQA90k")
@XmlAccessorType(XmlAccessType.FIELD)
public class Person {
@XmlElement
private long id;

@XmlElementWrapper(name = "academicTitles", namespace = "http://ift.tt/1ajV8z9")
@XmlElement(name = "academicTitle", namespace = "http://ift.tt/1ajV8z9")
private List<Type> academicTitles;

@XmlElement
private List<Type> otherTitles;
}


Type.java



@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(namespace = "http://ift.tt/1ajV8z9")
public class Type {
@XmlElement
private short value;
@XmlElement
private String text;
}


package-info.java



@XmlSchema(
xmlns = {
@XmlNs(namespaceURI = "http://ift.tt/1EQA90k", prefix = ""),
@XmlNs(namespaceURI = "http://ift.tt/1ajV8z9", prefix = "bar"),
},
elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)

package model.person;

import javax.xml.bind.annotation.XmlNs;
import javax.xml.bind.annotation.XmlSchema;


So with this setup everything works fine. The problem is that when I remove @XmlType annotation from Type class appropriate namespace prefix is not applied to fields of Type anymore. Is there a way to tell JAXB to apply namespace on Person level when declaring lists?


No comments:

Post a Comment