Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAX-B - How to map a schema element to an existing Java class [duplicate]

Tags:

java

jaxb

Possible Duplicate:
jaxb xjc mapping to existing domain objects

I am using JAX-B to generate Java classes from an XML schema.

There is one element in my schema that I would like to bind to a Java class that exists in my project. My binding is done in a .xjb file. I have tried several approaches but can't get anything to work.

Is this possible? If so, how?

Here is a smaller example of my problem:

My Existing Java class:

package com.existing; 

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;

@XmlAccessorType(XmlAccessType.FIELD)
public class Existing {
    private String prop; 
    public String getProp() { return prop; }
    public void setProp(String prop) { this.prop = prop; }
}

My Schema:

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
     targetNamespace="http://www.baloiselife.com/xpression/policy"
     xmlns="http://www.baloiselife.com/xpression/policy" >

<xs:element name="root_node">
  <xs:complexType>
    <xs:sequence>
      <xs:element name="some_other_propery" type="xs:string"/>
      <!-- I want this element to map onto my existing Java class -->
      <xs:element name="special_element" type="existing_type" minOccurs="0" />
    </xs:sequence>
  </xs:complexType>
</xs:element>

<!-- I want this element to be ignored, and instead my Java class used -->
<xs:complexType name="existing_type">
  <xs:sequence>
    <xs:element name="prop" type="xs:string" minOccurs="0" />
  </xs:sequence>
</xs:complexType>

So any ideas what my binding should be? I tried using the jxb:class setting, but could not get it to work. My end result has two requirements:

  1. The ExistingType class is not generated from the Schema
  2. The RootNode class has an element of type Existing, which maps to my existing Java class
like image 201
Jen S. Avatar asked Oct 15 '12 08:10

Jen S.


1 Answers

You can use an external binding file to configure XJC to do what you want.

binding.xjb

<jxb:bindings 
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:jxb="http://java.sun.com/xml/ns/jaxb"
    version="2.1">

    <jxb:bindings schemaLocation="yourSchema.xsd">
        <jxb:bindings node="//xs:complexType[@name='existing_type']">
            <jxb:class ref="com.existing.Existing"/>
        </jxb:bindings>
    </jxb:bindings>
</jxb:bindings>

XJC Call

xjc -d outputDir -b binding.xjb yourSchema.xsd
like image 148
bdoughan Avatar answered Oct 27 '22 22:10

bdoughan