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
302 views
in Technique[技术] by (71.8m points)

JAXB: How to change XJC-generated classes names when attr type is specified in XSD?

I'm a beginner to JAXB and I'm having annoying issues when generating Java classes with xjc. I am provided with a XSD like this:

<xs:element name="item" type="itemType"/>  
...   
<xs:complexType name="itemType">
    <xs:attribute name="id" type="xs:string" use="required">
    ...     
</xs:complexType>

and xjc is generating a class called ItemType.java, but I want the name to be Item.java. That is, I want the generated classes as if the XSD was like this:

<xs:element name="item">
    <xs:complexType>
    <xs:attribute name="id" type="xs:string" use="required">
        ...
    </xs:complexType>
</xs:element>

There won't be any reuse of itemType on any other element, it's just the people that constructs the XSD likes it this way. I guess there may be a way to do it with custom bindings but I still haven't found how.

Any help?

Thanks, Miguel

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

JAXB provides two ways to accomplish this:

1. Inline Schema Anntotations

You can use JAXB schema annotations to control the class names.

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

    <xs:complexType name="itemType">
        <xs:annotation>
            <xs:appinfo>
                <jaxb:class name="Item"/>
            </xs:appinfo>
        </xs:annotation>
        <xs:attribute name="id" type="xs:string" use="required"/>
    </xs:complexType>

</xs:schema>

2. External Binding File

This customization can also be done via and external binding file:

<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="your-schema.xsd">
            <jxb:bindings node="//xs:complexType[@name='itemType']">
                <jxb:class name="Item"/>
            </jxb:bindings>
    </jxb:bindings>

</jxb:bindings>

The xjc command line would be:

xjc -d out -b binding.xml your-schema.xsd

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

...