JAXB让Java与XML之间繁琐的机械编码成为过去,现在可以简单的通过XSD文件生成对应的Java文件,我一般使用maven-jaxb2-plugin来实现xsd到java文件的生成。
POM配置
指定xsd文件路径,制定binding文件路径,指定生成java文件路径
<plugin>
<groupId>org.jvnet.jaxb2.maven2</groupId>
<artifactId>maven-jaxb2-plugin</artifactId>
<version>0.9.0</version>
<executions>
<execution>
<id>schema1-generate</id>
<goals>
<goal>generate</goal>
</goals>
<configuration>
<schemaDirectory>src/main/resources/dir1</schemaDirectory>
<schemaIncludes>
<include>1.xsd</include>
</schemaIncludes>
<extension>true</extension>
<generateDirectory>${project.build.directory}/generated-sources/xjc1</generateDirectory>
<episodeFile>${project.build.directory}/generated-sources/xjc1/META-INF/1.episode</episodeFile>
<bindingDirectory>src/main/resources/dir1</bindingDirectory>
<bindingIncludes>
<include>1.xjb</include>
</bindingIncludes>
</configuration>
</execution>
</executions>
</plugin>
binding.xjb配置
实现类型匹配,包匹配,如果类型匹配复杂,可能需要实现自己的转换类
<jaxb:bindings xmlns:jaxb="http://java.sun.com/xml/ns/jaxb" xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"
xmlns:xs="http://www.w3.org/2001/XMLSchema" version="2.0" schemaLocation="book.xsd">
<jaxb:globalBindings
fixedAttributeAsConstantProperty="true"
typesafeEnumBase="xs:string"
typesafeEnumMemberName="generateName"
generateIsSetMethod="true">
<!--
<xjc:noValidator
/>
<xjc:noValidatingUnmarshaller
/>
-->
<xjc:serializable uid="1" />
<jaxb:javaType name="java.util.Calendar" xmlType="xs:dateTime" parseMethod="javax.xml.bind.DatatypeConverter.parseDateTime" printMethod="javax.xml.bind.DatatypeConverter.printDateTime" />
</jaxb:globalBindings>
<jaxb:schemaBindings schemaLocation="1.xsd" node="/xs:schema">
<jaxb:package name="com.cloud" />
</jaxb:schemaBindings>
</jaxb:bindings>
Note1: 新版本的plugin不止可以生成java class,还可以帮忙生成object的最重要的几个方法:toString, equals, hashCode, clone,只要在configuration里配置对于的plugin就可以了
<configuration>
<extension>true</extension>
<args>
<arg>-XtoString</arg>
<arg>-Xequals</arg>
<arg>-XhashCode</arg>
<arg>-Xcopyable</arg>
</args>
<plugins>
<plugin>
<groupId>org.jvnet.jaxb2_commons</groupId>
<artifactId>jaxb2-basics</artifactId>
<version><!-- version 0.9.0--></version>
</plugin>
</plugins>
</configuration>
Note2: 我遇到过同一个项目中2个xsd文件有同样的node type,不同的内容,虽然指定了不同包来generate source还是报错,最后的解决方案是用2个execution分别解析不同的xsd文件,不过我使用cxf插件就没有遇到这个问题,可以在一个execution里面生成想要的所有Java class。
原文地址:http://blog.csdn.net/cloud_ll/article/details/44123727