JAXB java class generation from schema: how to get a custom XML element name (keep class name)

774 Views Asked by At

I have an XSD with an element - it is the XMLRootElement if that makes a difference - like this:

<xsd:element name= "SomeElement">

I need to have the generated Java class have a custom XML element name while keeping the default Java class name, so the generated class needs to look like this:

@XmlRootElement(name = "fo:SomeElement")
public class SomeElement

So that marshal/unmarshalled xml elements will show as

<fo:SomeElement>

Can someone help me out with what I need to change to either the XSD file or the binding file?

1

There are 1 best solutions below

0
On

First of all, with your question you opened a big can of worms. Things are more complicated than you thought they would be. To fully understand the rest of this answer you will surely need to learn more about the namespace concept in XML, for example at w3schools.com - XML Namespaces. Having said that, the following stuff should give a quick entry into that topic.

Note that fo:SomeElement is not directly an XML element name. The fo: is a so-called namespace-prefix. The namespace-prefix needs to be mapped to a namespace-URI by xmlns:fo="...",

By convention fo: is the namespace-prefix used for XSL Formatting Objects. Therefore most probably your XML file will look like this:

<fo:SomeElement xmlns:fo="http://www.w3.org/1999/XSL/Format" ...>
    ...
</fo:SomeElement>

Note that "http://www.w3.org/1999/XSL/Format" is the namespace-URI as specified in the XSL Formatting Objects specification.

Note also, that namespace-prefixes (here fo) by themselves are irrelevant and were only invented to make the XML content easier to read for humans. So instead of fo you might as well have used bla in all places as the namespace-prefix, and the XML content still would have the exact same meaning. The only relevant things are the namespace-URIs (here "http://www.w3.org/1999/XSL/Format").

With JAXB the correct Java root class would look like this. Note the namespace given in the @XmlRootElement annotation.

@XmlRootElement(name="SomeElement", namespace="http://www.w3.org/1999/XSL/Format")
public class SomeElement {
   ...
}

You would need to specify this namespace-URI not only in @XmlRootElement, but also for nested Java properties corresponding to any <fo:something> XML content. Fur this purpose most JAXB annotations (@XmlElement, @XmlAttribute, ...) can accept a namespace parameter as well.

The XML schema definition (XSD) consistent with the XML example and the Java class above would look like this. Note the targetNamespace given in the <xs:schema> element.

<xs:schema version="1.0" targetNamespace="http://www.w3.org/1999/XSL/Format"
                         xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="SomeElement">
    ...
  </xs:element>
</xs:schema>