help please: xjc throws "Two declarations cause a collision in the ObjectFactory class"

Mike picture Mike · Sep 20, 2011 · Viewed 8.5k times · Source

Take the following over simplified XSD:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema targetNamespace="com.acme" xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name="Widget">
        <xs:complexType>
            <xs:sequence>
                <xs:element 
                    minOccurs="0" name="color" nillable="true" type="xs:string" />
            </xs:sequence>
        </xs:complexType>
    </xs:element>
    <xs:element name="WidgetColor" type="xs:string" />
</xs:schema>

Then, attempt the following:

xjc test.xsd

You should invariably get the following exception:

parsing a schema...
compiling a schema...
[ERROR] Two declarations cause a collision in the ObjectFactory class.
  line 11 of file:/C:/test.xsd

[ERROR] (Related to above error) This is the other declaration.
  line 7 of file:/C:/test.xsd

Failed to produce code.

Notice that There is an element name "Widget" which is a complexType and has elements named "color". There is also, at the same level as the element "Widget", an simple element named "WidgetColor".

What is more puzzling is that if you remove the attribute minOccurs="0" OR you remove the attribute nillable="true" from the "color" element sequence, xjc compiles the schema successfully.

Has anyone ever seen this problem or can suggest a solution?

Thanks,

Mike.

Answer

Mike picture Mike · Sep 21, 2011

Well I finally figured out how to fix my problem. It lies in using a custom binding to specify a distinct class name for one of the declarations.

Content of custom-binding.xjb

<?xml version="1.0" encoding="UTF-8"?>
<bindings version="2.0" xmlns="http://java.sun.com/xml/ns/jaxb" xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <bindings schemaLocation="test.xsd">
        <bindings node="//xs:element[@name='WidgetColor']">
            <class name="BaseWidgetColor" />
        </bindings>
    </bindings>
</bindings>

Operation:

C:\>xjc -b custom-binding.xjb test.xsd
parsing a schema...
compiling a schema...
acme\com\BaseWidgetColor.java
acme\com\ObjectFactory.java
acme\com\Widget.java
acme\com\package-info.java

Patience et longueur de temps valent mieux que rage et acharnement...!