使用Eclipse从JAXB Java类生成XSD

学习使用Eclipse IDE 从带有JAXB注解的Java类创建XML模式文档(xsd)

1)将JAXB注解添加到Java类

第一步是注解,比如添加@XmlRootElement@XmlAccessorType@XmlElement等来你的Java类。

import java.io.Serializable;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "employee")
@XmlAccessorType(XmlAccessType.PROPERTY)
public class Employee implements Serializable {

	private static final long serialVersionUID = 1L;
	
	private Integer id;
	private String firstName;
	private String lastName;
	private Department department;
	
	public Employee() {
		super();
	}

	//Setters and Getters
}
import java.io.Serializable;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "department")
@XmlAccessorType(XmlAccessType.PROPERTY)
public class Department implements Serializable {
	
	private static final long serialVersionUID = 1L;
	
	Integer id;
	String name;
	
	public Department() {
		super();
	}

	//Setters and Getters
}

2)从JAXB类生成XSD

2.1)导航到Eclipse选项

JAXB类选项的模式
JAXB类选项的模式

2.2)选择生成的模式文件的位置

生成的模式文件的位置
生成的模式文件的位置

2.3)选择JAXB类

选择JAXB类
选择JAXB类

2.4)生成xsd文件

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<xs:schema version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema">

  <xs:element name="department" type="department"/>

  <xs:element name="employee" type="employee"/>

  <xs:complexType name="employee">
    <xs:sequence>
      <xs:element ref="department" minOccurs="0"/>
      <xs:element name="firstName" type="xs:string" minOccurs="0"/>
      <xs:element name="id" type="xs:int" minOccurs="0"/>
      <xs:element name="lastName" type="xs:string" minOccurs="0"/>
    </xs:sequence>
  </xs:complexType>

  <xs:complexType name="department">
    <xs:sequence>
      <xs:element name="id" type="xs:int" minOccurs="0"/>
      <xs:element name="name" type="xs:string" minOccurs="0"/>
    </xs:sequence>
  </xs:complexType>
</xs:schema>

XSd文件已生成,现在您可以将其用于各种应用程序用例。

saigon has written 1440 articles

Leave a Reply