Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
487 views
in Technique[技术] by (71.8m points)

xsd - XJC Generating Integer Instead of int

The following schema should be generating two primitive int fields in a Value class, but instead generates a primitive int for the element and java.lang.Integer for the attribute.

<?xml version="1.0" encoding="UTF-8"?>

<xsd:schema version="1.0" xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    targetNamespace="http://www.example.com/test" xmlns:test="http://www.example.com/test"
    elementFormDefault="qualified">

    <xsd:element name="values">
        <xsd:complexType>
            <xsd:sequence minOccurs="0" maxOccurs="unbounded">
                <xsd:element ref="test:value" />
            </xsd:sequence>
        </xsd:complexType>
    </xsd:element>

    <xsd:element name="value">
        <xsd:complexType>
            <xsd:sequence>
                <!-- Is generated as primitive int -->
                <xsd:element name="element" type="xsd:int" />
            </xsd:sequence>
            <!-- Is generated as java.lang.Integer -->
            <xsd:attribute name="attribute" type="xsd:int" />
        </xsd:complexType>
    </xsd:element>

</xsd:schema>

I've looked through the JAXB documentation for anything that says that attributes and elements may be generated differently and found nothing.

Can anyone explain this? Is there a fix to make the attribute generate as a primitive int?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I'm not entirely sure this is the answer, but I had an epiphany while debugging my app.

The default multiplicity for an element in an XML schema is 1..1 (required) where as the default multiplicity for an attribute is 0..1 (optional).

  1. So, since the element is required and a primitive in Java has a default value (most likely 0), it makes sense to generate an <xsd:element type="xsd:int" /> as a Java primitive.

  2. Since the attribute is optional there is a possibility that it may be nillable which would not be possible using a primitive. The java.lang.Integer is an Object and thus allowed to be null, so it makes sense to generate an <xsd:attribute type="xsd:int" /> as an java.lang.Integer.

If you make an attribute be required (<xsd:attribute type="xsd:int" use="required" />), it will generate as a primitive int. I haven't seen documentation by JAXB that explicitly says this, but that doesn't mean it doesn't exist; perhaps I just missed it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...