本文介绍利用jaxb2-maven-plugin插件,直接从xsd文件生成对应的Java class。从而实现在webservice的开发中,能更方便的实现Java class和XML之间的转换。
1.创建xsd文件
2.编写pom.xml 文件
(1)指定生成Java class所利用的xsd文件的位置,本例中需要把上文的hr.xsd文件放到/src/main/resources/ 目录下。
(2)指定生成文件的输出位置。
[b]生成的Java class类package采用xsd文件中指定的schema的targetNamespace,本例中就是com.fengyilin.hr.schemas
[/b]
工程目录如下:
[img]http://dl2.iteye.com/upload/attachment/0121/8875/50ac9c47-85b2-3ca0-9814-0d07b7735967.png[/img]
3.在工程的根目录下执行 mvn compile
执行完成后会在src/main/java/com/fengyilin/hr/schemas/ 下生成对应的Java class
执行后的工程目录如下:
[img]http://dl2.iteye.com/upload/attachment/0121/8877/993feea9-0b46-3074-93f9-2735e8e00584.png[/img]
4.生成的代码列举:
[color=red]Java中直接和xsd中xs:date对应的类型是XMLGregorianCalendar,无法在开发中使用,所以此处生成后手工替换成了实际开发中的类型java.util.Date[/color]
4.利用生成后的Java class实现和XML的转换
转换工具类:
Test类:
执行结果:
1.创建xsd文件
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:hr="http://fengyilin.com/hr/schemas" elementFormDefault="qualified"
targetNamespace="http://fengyilin.com/hr/schemas">
<xs:element name="HolidayRequest">
<xs:complexType>
<xs:all>
<xs:element name="Holiday" type="hr:HolidayType" />
<xs:element name="Employee" type="hr:EmployeeType" />
</xs:all>
</xs:complexType>
</xs:element>
<xs:element name="HolidayResponse">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string" />
<xs:element name="number" type="xs:integer" />
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:complexType name="HolidayType">
<xs:sequence>
<xs:element name="StartDate" type="xs:date" />
<xs:element name="EndDate" type="xs:date" />
</xs:sequence>
</xs:complexType>
<xs:complexType name="EmployeeType">
<xs:sequence>
<xs:element name="Number" type="xs:integer" />
<xs:element name="FirstName" type="xs:string" />
<xs:element name="LastName" type="xs:string" />
</xs:sequence>
</xs:complexType>
</xs:schema>
2.编写pom.xml 文件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.fengyilin</groupId>
<artifactId>xsdtojava</artifactId>
<version>0.1.0</version>
<properties>
<java.version>1.8</java.version>
</properties>
<build>
<plugins>
<!-- tag::xsd[] -->
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>jaxb2-maven-plugin</artifactId>
<version>1.6</version>
<executions>
<execution>
<id>xjc</id>
<goals>
<goal>xjc</goal>
</goals>
</execution>
</executions>
<configuration>
<schemaDirectory>${project.basedir}/src/main/resources/</schemaDirectory> (1)
<outputDirectory>${project.basedir}/src/main/java</outputDirectory> (2)
<clearOutputDir>false</clearOutputDir>
</configuration>
</plugin>
<!-- end::xsd[] -->
</plugins>
</build>
</project>
(1)指定生成Java class所利用的xsd文件的位置,本例中需要把上文的hr.xsd文件放到/src/main/resources/ 目录下。
(2)指定生成文件的输出位置。
[b]生成的Java class类package采用xsd文件中指定的schema的targetNamespace,本例中就是com.fengyilin.hr.schemas
[/b]
工程目录如下:
[img]http://dl2.iteye.com/upload/attachment/0121/8875/50ac9c47-85b2-3ca0-9814-0d07b7735967.png[/img]
3.在工程的根目录下执行 mvn compile
执行完成后会在src/main/java/com/fengyilin/hr/schemas/ 下生成对应的Java class
执行后的工程目录如下:
[img]http://dl2.iteye.com/upload/attachment/0121/8877/993feea9-0b46-3074-93f9-2735e8e00584.png[/img]
4.生成的代码列举:
//
// 此文件是由 JavaTM Architecture for XML Binding (JAXB) 引用实现 v2.2.7 生成的
// 请访问 <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// 在重新编译源模式时, 对此文件的所有修改都将丢失。
// 生成时间: 2016.12.10 时间 07:16:22 PM CST
//
package com.fengyilin.hr.schemas;
import java.math.BigInteger;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>anonymous complex type的 Java 类。
*
* <p>以下模式片段指定包含在此类中的预期内容。
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="name" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="number" type="{http://www.w3.org/2001/XMLSchema}integer"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"name",
"number"
})
@XmlRootElement(name = "HolidayResponse")
public class HolidayResponse {
@XmlElement(required = true)
protected String name;
@XmlElement(required = true)
protected BigInteger number;
/**
* 获取name属性的值。
*
* @return
* possible object is
* {@link String }
*
*/
public String getName() {
return name;
}
/**
* 设置name属性的值。
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setName(String value) {
this.name = value;
}
/**
* 获取number属性的值。
*
* @return
* possible object is
* {@link BigInteger }
*
*/
public BigInteger getNumber() {
return number;
}
/**
* 设置number属性的值。
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setNumber(BigInteger value) {
this.number = value;
}
}
//
// 此文件是由 JavaTM Architecture for XML Binding (JAXB) 引用实现 v2.2.7 生成的
// 请访问 <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// 在重新编译源模式时, 对此文件的所有修改都将丢失。
// 生成时间: 2016.12.10 时间 07:16:22 PM CST
//
package com.fengyilin.hr.schemas;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>anonymous complex type的 Java 类。
*
* <p>以下模式片段指定包含在此类中的预期内容。
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <all>
* <element name="Holiday" type="{http://fengyilin.com/hr/schemas}HolidayType"/>
* <element name="Employee" type="{http://fengyilin.com/hr/schemas}EmployeeType"/>
* </all>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
})
@XmlRootElement(name = "HolidayRequest")
public class HolidayRequest {
@XmlElement(name = "Holiday", required = true)
protected HolidayType holiday;
@XmlElement(name = "Employee", required = true)
protected EmployeeType employee;
/**
* 获取holiday属性的值。
*
* @return
* possible object is
* {@link HolidayType }
*
*/
public HolidayType getHoliday() {
return holiday;
}
/**
* 设置holiday属性的值。
*
* @param value
* allowed object is
* {@link HolidayType }
*
*/
public void setHoliday(HolidayType value) {
this.holiday = value;
}
/**
* 获取employee属性的值。
*
* @return
* possible object is
* {@link EmployeeType }
*
*/
public EmployeeType getEmployee() {
return employee;
}
/**
* 设置employee属性的值。
*
* @param value
* allowed object is
* {@link EmployeeType }
*
*/
public void setEmployee(EmployeeType value) {
this.employee = value;
}
}
//
// 此文件是由 JavaTM Architecture for XML Binding (JAXB) 引用实现 v2.2.7 生成的
// 请访问 <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// 在重新编译源模式时, 对此文件的所有修改都将丢失。
// 生成时间: 2016.12.10 时间 07:16:22 PM CST
//
package com.fengyilin.hr.schemas;
import java.math.BigInteger;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>EmployeeType complex type的 Java 类。
*
* <p>以下模式片段指定包含在此类中的预期内容。
*
* <pre>
* <complexType name="EmployeeType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="Number" type="{http://www.w3.org/2001/XMLSchema}integer"/>
* <element name="FirstName" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="LastName" type="{http://www.w3.org/2001/XMLSchema}string"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "EmployeeType", propOrder = {
"number",
"firstName",
"lastName"
})
public class EmployeeType {
@XmlElement(name = "Number", required = true)
protected BigInteger number;
@XmlElement(name = "FirstName", required = true)
protected String firstName;
@XmlElement(name = "LastName", required = true)
protected String lastName;
/**
* 获取number属性的值。
*
* @return
* possible object is
* {@link BigInteger }
*
*/
public BigInteger getNumber() {
return number;
}
/**
* 设置number属性的值。
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setNumber(BigInteger value) {
this.number = value;
}
/**
* 获取firstName属性的值。
*
* @return
* possible object is
* {@link String }
*
*/
public String getFirstName() {
return firstName;
}
/**
* 设置firstName属性的值。
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setFirstName(String value) {
this.firstName = value;
}
/**
* 获取lastName属性的值。
*
* @return
* possible object is
* {@link String }
*
*/
public String getLastName() {
return lastName;
}
/**
* 设置lastName属性的值。
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setLastName(String value) {
this.lastName = value;
}
}
//
// 此文件是由 JavaTM Architecture for XML Binding (JAXB) 引用实现 v2.2.7 生成的
// 请访问 <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// 在重新编译源模式时, 对此文件的所有修改都将丢失。
// 生成时间: 2016.12.10 时间 07:16:22 PM CST
//
package com.fengyilin.hr.schemas;
import java.util.Date;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>HolidayType complex type的 Java 类。
*
* <p>以下模式片段指定包含在此类中的预期内容。
*
* <pre>
* <complexType name="HolidayType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="StartDate" type="{http://www.w3.org/2001/XMLSchema}date"/>
* <element name="EndDate" type="{http://www.w3.org/2001/XMLSchema}date"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "HolidayType", propOrder = {
"startDate",
"endDate"
})
public class HolidayType {
@XmlElement(name = "StartDate", required = true)
@XmlSchemaType(name = "date")
protected Date startDate;
@XmlElement(name = "EndDate", required = true)
@XmlSchemaType(name = "date")
protected Date endDate;
/**
* 获取startDate属性的值。
*
* @return
* possible object is
* {@link Date }
*
*/
public Date getStartDate() {
return startDate;
}
/**
* 设置startDate属性的值。
*
* @param value
* allowed object is
* {@link Date }
*
*/
public void setStartDate(Date value) {
this.startDate = value;
}
/**
* 获取endDate属性的值。
*
* @return
* possible object is
* {@link Date }
*
*/
public Date getEndDate() {
return endDate;
}
/**
* 设置endDate属性的值。
*
* @param value
* allowed object is
* {@link Date }
*
*/
public void setEndDate(Date value) {
this.endDate = value;
}
}
[color=red]Java中直接和xsd中xs:date对应的类型是XMLGregorianCalendar,无法在开发中使用,所以此处生成后手工替换成了实际开发中的类型java.util.Date[/color]
//
// 此文件是由 JavaTM Architecture for XML Binding (JAXB) 引用实现 v2.2.7 生成的
// 请访问 <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// 在重新编译源模式时, 对此文件的所有修改都将丢失。
// 生成时间: 2016.12.10 时间 07:16:22 PM CST
//
package com.fengyilin.hr.schemas;
import javax.xml.bind.annotation.XmlRegistry;
/**
* This object contains factory methods for each
* Java content interface and Java element interface
* generated in the com.fengyilin.hr.schemas package.
* <p>An ObjectFactory allows you to programatically
* construct new instances of the Java representation
* for XML content. The Java representation of XML
* content can consist of schema derived interfaces
* and classes representing the binding of schema
* type definitions, element declarations and model
* groups. Factory methods for each of these are
* provided in this class.
*
*/
@XmlRegistry
public class ObjectFactory {
/**
* Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: com.fengyilin.hr.schemas
*
*/
public ObjectFactory() {
}
/**
* Create an instance of {@link HolidayRequest }
*
*/
public HolidayRequest createHolidayRequest() {
return new HolidayRequest();
}
/**
* Create an instance of {@link HolidayType }
*
*/
public HolidayType createHolidayType() {
return new HolidayType();
}
/**
* Create an instance of {@link EmployeeType }
*
*/
public EmployeeType createEmployeeType() {
return new EmployeeType();
}
/**
* Create an instance of {@link HolidayResponse }
*
*/
public HolidayResponse createHolidayResponse() {
return new HolidayResponse();
}
}
//
// 此文件是由 JavaTM Architecture for XML Binding (JAXB) 引用实现 v2.2.7 生成的
// 请访问 <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// 在重新编译源模式时, 对此文件的所有修改都将丢失。
// 生成时间: 2016.12.10 时间 07:16:22 PM CST
//
@javax.xml.bind.annotation.XmlSchema(namespace = "http://fengyilin.com/hr/schemas", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
package com.fengyilin.hr.schemas;
4.利用生成后的Java class实现和XML的转换
转换工具类:
package util;
import java.io.StringReader;
import java.io.StringWriter;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
public class JaxbUtil {
public static String convertToXml(Object obj) {
return convertToXml(obj, "UTF-8");
}
/**
* 将Java对象转换成对应的xml
* @param obj
* @param encoding
* @return
*/
public static String convertToXml(Object obj, String encoding) {
String result = null;
try {
JAXBContext context = JAXBContext.newInstance(obj.getClass());
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);
StringWriter writer = new StringWriter();
marshaller.marshal(obj, writer);
result = writer.toString();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 从xml转换成对应的Java object
* @param xml
* @param c
* @return
*/
@SuppressWarnings("unchecked")
public static <T> T converToJavaBean(String xml, Class<T> c) {
T t = null;
try {
JAXBContext context = JAXBContext.newInstance(c);
Unmarshaller unmarshaller = context.createUnmarshaller();
t = (T) unmarshaller.unmarshal(new StringReader(xml));
} catch (Exception e) {
e.printStackTrace();
}
return t;
}
}
Test类:
import java.util.Date;
import com.fengyilin.hr.schemas.EmployeeType;
import com.fengyilin.hr.schemas.HolidayRequest;
import com.fengyilin.hr.schemas.HolidayType;
import util.JaxbUtil;
public class Test {
public static void main(String[] args) {
HolidayRequest request = new HolidayRequest();
EmployeeType employee = new EmployeeType();
employee.setFirstName("feng");
employee.setLastName("yilin");
request.setEmployee(employee);
HolidayType holiday = new HolidayType();
holiday.setEndDate(new Date());
holiday.setStartDate(new Date());
request.setHoliday(holiday);
System.out.println(JaxbUtil.convertToXml(request));
}
}
执行结果:
<HolidayRequest xmlns="http://fengyilin.com/hr/schemas">
<Holiday>
<StartDate>2016-12-10+08:00</StartDate>
<EndDate>2016-12-10+08:00</EndDate>
</Holiday>
<Employee>
<FirstName>feng</FirstName>
<LastName>yilin</LastName>
</Employee>
</HolidayRequest>