Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Customize object/element name with JAXB

I'm very new to JAXB, so I'm having trouble cracking this (I assume) very simple use case.

I have a set of schemas I got. I have no control over those, I cannot change them. In these schemas, I have declarations such as

<xs:complexType name="CustomerType">
    ...

I try to generate classes from these. So such a declaration becomes

@XmlType(name = "CustomerType", propOrder = {
    "field1",
    "field2"
})
public class CustomerType {
    ...

Then I need to use this class to create XML messages using a RestTemplate. The problem is, the object in the XML message is not supposed to be "CustomerType", it's supposed to be just "Customer". Like I said, I cannot edit the schemas. I also cannot directly edit the generated sources. I need some kind of external customization that tells either the source generating process, or the marshalling process, how to transform the names of the objects. Any advice will be greatly appreciated.

like image 757
Sethiel Avatar asked Jun 13 '26 00:06

Sethiel


1 Answers

You can use bindings to customize class or property names. Typically you'll have a file like bindings.xjb like this:

<jaxb:bindings version="1.0" xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"
    jaxb:extensionBindingPrefixes="xjc">

    <jaxb:bindings schemaLocation="schema.xsd" node="/xsd:schema">
        <jaxb:bindings node="xsd:customType[@name='CustomerType']">
            <jaxb:class name="Customer"/>
        </jaxb:bindings>
        <jaxb:bindings node="xsd:customType[@name='CustomerType']//xsd:element[@name='field1']">
            <jaxb:property name="f1"/>
        </jaxb:bindings>
    </jaxb:bindings>
</jaxb:bindings>

There are quite a few things you can customize with bindings (see this), but certainly not everything.

like image 163
lexicore Avatar answered Jun 15 '26 15:06

lexicore