首页 > 代码库 > 使用org.eclipse.xsd.XSDEnumerationFacet生成枚举类型的Schema

使用org.eclipse.xsd.XSDEnumerationFacet生成枚举类型的Schema

因为网上关于Eclipse XSD的中文资料比较少,而且关于Eclipse XSD的范例代码也凤毛麟角,但是有的时候我们需要生成一个带枚举限定的简单类型的XSD Schema,比如下面的格式,

<?xml version="1.0" encoding="UTF-8"?><schema xmlns="http://www.w3.org/2001/XMLSchema"    targetNamespace="http://www.w3.org/2001/XMLSchema">
	  <complexType name="StudentType">
	    <sequence>
	      <element maxOccurs="1" minOccurs="1" name="username" type="string"/>
	      <element maxOccurs="1" minOccurs="1" name="password" type="string"/>
	      <element maxOccurs="1" minOccurs="1" name="alignment" type="AlignmentType"/>
	    </sequence>
	  </complexType>
	  <simpleType name="AlignmentType">
	    <restriction base="string">
	      <enumeration value=http://www.mamicode.com/"RIGHT"/>>


其中, <SimpleType name="AlignmentType"> 代表的就是一个带枚举限定的简单类型。那么应该如何生成呢?请见参考下面的代码。

import org.eclipse.xsd.XSDComplexTypeDefinition;
import org.eclipse.xsd.XSDCompositor;
import org.eclipse.xsd.XSDElementDeclaration;
import org.eclipse.xsd.XSDEnumerationFacet;
import org.eclipse.xsd.XSDFactory;
import org.eclipse.xsd.XSDImport;
import org.eclipse.xsd.XSDInclude;
import org.eclipse.xsd.XSDModelGroup;
import org.eclipse.xsd.XSDParticle;
import org.eclipse.xsd.XSDRedefine;
import org.eclipse.xsd.XSDSchema;
import org.eclipse.xsd.XSDSchemaDirective;
import org.eclipse.xsd.XSDSimpleTypeDefinition;
import org.eclipse.xsd.util.XSDResourceImpl;
import org.eclipse.xsd.util.XSDUtil;
import org.junit.Test;
import org.w3c.dom.Element;

public class EnumFacetTest {
   protected static XSDFactory xsdFactory = XSDFactory.eINSTANCE;
   private  void createAligementElement(XSDSimpleTypeDefinition  aligmentType){
   String[] cellAligements={"RIGHT","MIDDLE","LEFT"};
     for(int i=0;i<cellAligements.length;i++){
    	 XSDEnumerationFacet alEnum=XSDFactory.eINSTANCE.createXSDEnumerationFacet();
    	 alEnum.setLexicalValue(cellAligements[i]);
    	 //aligmentType.getFacets().add(alEnum);
    	 aligmentType.getFacetContents().add(alEnum);
     } 
   }
   /**
	<?xml version="1.0" encoding="UTF-8"?><schema xmlns="http://www.w3.org/2001/XMLSchema"    targetNamespace="http://www.w3.org/2001/XMLSchema">
	  <complexType name="StudentType">
	    <sequence>
	      <element maxOccurs="1" minOccurs="1" name="username" type="string"/>
	      <element maxOccurs="1" minOccurs="1" name="password" type="string"/>
	      <element maxOccurs="1" minOccurs="1" name="alignment" type="AlignmentType"/>
	    </sequence>
	  </complexType>
	  <simpleType name="AlignmentType">
	    <restriction base="string">
	      <enumeration value=http://www.mamicode.com/"RIGHT"/>>



使用org.eclipse.xsd.XSDEnumerationFacet生成枚举类型的Schema