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

xjc - Prefixing JAXB generated classes

I have this Maven "task" to generate Java classes from an XSD file using JAXB.

        <!-- XML to Java classes -->
        <plugin>
            <groupId>com.sun.tools.xjc.maven2</groupId>
            <artifactId>maven-jaxb-plugin</artifactId>
            <executions>
                <execution>
                    <phase>generate-sources</phase>
                    <goals>
                        <goal>generate</goal>
                    </goals>
                </execution>
            </executions>
            <configuration>
                <generatePackage>nl.compay.service</generatePackage>
                <schemaDirectory>src/main/webapp/compay</schemaDirectory>
            </configuration>
        </plugin>

For an XSD type "User", it generates a class named "User" (duh). However, I also have a JPA entity class called "User" (though in a different package). Can I change the XML config above to let JAXB prefix the generated classes with something like "XML"?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

This is a common requirement. You can do that by providing an additional JAXB binding file to customize how JAXB translates the Schema type names into Java class names.

These files normally end in extension ".xjb". You need to create one for your schema, for example:

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

    <jxb:bindings schemaLocation="nl.company.service.xsd" node="/xs:schema">
        <jxb:schemaBindings>
            <jxb:nameXmlTransform>
                <jxb:typeName prefix="XML"/>
                <jxb:anonymousTypeName prefix="XML"/>
            </jxb:nameXmlTransform>
        </jxb:schemaBindings>
    </jxb:bindings>

</jxb:bindings>

After you've done that, drop the xjb file somewhere in your build directory and tell Maven to make use of it during translation:

<includeBindings>
    <includeBinding>mybindings.xjb</includeBinding>
</includeBindings>

And here's a hint for the road: if you are in a path that contains spaces (e.g. "Documents and Settingsuserproject") then JAXB will fall over with strange errors.


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

...