使用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="RIGHT"/>
	      <enumeration value="MIDDLE"/>
	      <enumeration value="LEFT"/>
	    </restriction>
	  </simpleType>
	  <element name="Student" type="StudentType"/>
	</schema>

其中, <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="RIGHT"/>
	      <enumeration value="MIDDLE"/>
	      <enumeration value="LEFT"/>
	    </restriction>
	  </simpleType>
	  <element name="Student" type="StudentType"/>
	</schema>
    */
    @Test
    public void EnumFacetTest() {
    	String targeNameSpace="http://www.w3.org/2001/XMLSchema";
		XSDSchema xsdSchema=xsdFactory.createXSDSchema();
		xsdSchema.setTargetNamespace(targeNameSpace);
		xsdSchema.getQNamePrefixToNamespaceMap().put(null, "http://www.w3.org/2001/XMLSchema");

		//1.1 Create Complex type:student
		XSDComplexTypeDefinition complexTypeDef = xsdFactory.createXSDComplexTypeDefinition();
		complexTypeDef.setTargetNamespace(xsdSchema.getTargetNamespace());
		complexTypeDef.setName("StudentType");

		XSDParticle xsdParticle=xsdFactory.createXSDParticle();
		XSDModelGroup xsdModuleGroup=xsdFactory.createXSDModelGroup();
		xsdModuleGroup.setCompositor(XSDCompositor.SEQUENCE_LITERAL);

		xsdParticle.setContent(xsdModuleGroup);

		complexTypeDef.setContent(xsdParticle);
		complexTypeDef.setContentType(xsdParticle);
		xsdSchema.getContents().add(complexTypeDef);

		//1.2 Add element for complex type
		//1.2.1 username element
		XSDParticle localXSDParticle = xsdFactory.createXSDParticle();
		localXSDParticle.setMinOccurs(1);
		localXSDParticle.setMaxOccurs(1);
		XSDElementDeclaration localXSDElementDeclaration = xsdFactory.createXSDElementDeclaration();
		localXSDElementDeclaration.setTargetNamespace(targeNameSpace);
		localXSDElementDeclaration.setName("username");
		XSDSchema localXSDSchema = XSDUtil.getSchemaForSchema("http://www.w3.org/2001/XMLSchema");
		XSDSimpleTypeDefinition localSimpleType=localXSDSchema.resolveSimpleTypeDefinition("string");
		localXSDElementDeclaration.setTypeDefinition(localSimpleType);
		localXSDParticle.setContent(localXSDElementDeclaration);
		xsdModuleGroup.getContents().add(localXSDParticle);

		//1.2.2 password element
		localXSDParticle = xsdFactory.createXSDParticle();
		localXSDParticle.setMinOccurs(1);
		localXSDParticle.setMaxOccurs(1);
		localXSDElementDeclaration = xsdFactory.createXSDElementDeclaration();
		localXSDElementDeclaration.setTargetNamespace(targeNameSpace);
		localXSDElementDeclaration.setName("password");
		localXSDSchema = XSDUtil.getSchemaForSchema("http://www.w3.org/2001/XMLSchema");
		localSimpleType=localXSDSchema.resolveSimpleTypeDefinition("string");
		localXSDElementDeclaration.setTypeDefinition(localSimpleType);
		localXSDParticle.setContent(localXSDElementDeclaration);
		xsdModuleGroup.getContents().add(localXSDParticle);

		//1.2.3.1 Create Simple Type with XSDEnumerationFacet---------------
		 XSDSimpleTypeDefinition xsdSimpleTypeDefinition = XSDFactory.eINSTANCE.createXSDSimpleTypeDefinition();
		 XSDSimpleTypeDefinition baseTypeDefinition =  xsdSchema.resolveSimpleTypeDefinitionURI("string");
		 xsdSimpleTypeDefinition.setBaseTypeDefinition(baseTypeDefinition);
	     xsdSimpleTypeDefinition.setName("AlignmentType");
		 createAligementElement(xsdSimpleTypeDefinition);
		 xsdSchema.getContents().add(xsdSimpleTypeDefinition);
		//1.2.3.2 Create element with Simple Type --------------
		  localXSDParticle = xsdFactory.createXSDParticle();
		  localXSDParticle.setMinOccurs(1);
		  localXSDParticle.setMaxOccurs(1);
		  localXSDElementDeclaration = xsdFactory.createXSDElementDeclaration();
		  localXSDElementDeclaration.setTargetNamespace(targeNameSpace);
		  localXSDElementDeclaration.setName("alignment");
		  localXSDSchema = XSDUtil.getSchemaForSchema("http://www.w3.org/2001/XMLSchema");
		  localXSDElementDeclaration.setTypeDefinition(xsdSimpleTypeDefinition);
		  localXSDParticle.setContent(localXSDElementDeclaration);
		  xsdModuleGroup.getContents().add(localXSDParticle);

		//2.Create XSDElementDeclaration and attached complex type to XSD element
		XSDElementDeclaration xsdEelement=xsdFactory.createXSDElementDeclaration();
		xsdEelement.setName("Student");
		xsdEelement.setTypeDefinition(complexTypeDef);
		xsdSchema.getContents().add(xsdEelement);

		//3.Print Schema
		SchemaPrintService.printSchema(xsdSchema);

	}
}

class SchemaPrintService {
	/**
	 * print schema to console
	 *
	 * @param xsdSchema
	 */
	public static void printSchema(XSDSchema xsdSchema) {
		System.out.println("<!-- ===== Schema Composition =====");
		printDirectives("  ", xsdSchema);
		System.out.println("-->");

		System.out
				.println("<!-- [ " + xsdSchema.getSchemaLocation() + " ] -->");
		xsdSchema.updateElement();
		Element element = xsdSchema.getElement();
		if (element != null) {
			// Print the serialization of the model.
			XSDResourceImpl.serialize(System.out, element);
		}
	}

	private static void printSchemaStart(XSDSchema xsdSchema) {
		System.out.print("<schema targetNamespace=\"");
		if (xsdSchema.getTargetNamespace() != null) {
			System.out.print(xsdSchema.getTargetNamespace());
		}
		System.out.print("\" schemaLocation=\"");
		if (xsdSchema.getSchemaLocation() != null) {
			System.out.print(xsdSchema.getSchemaLocation());
		}
		System.out.print("\">");
	}

	private static void printDirectives(String indent, XSDSchema xsdSchema) {
		System.out.print(indent);
		printSchemaStart(xsdSchema);
		System.out.println();

		if (!xsdSchema.getReferencingDirectives().isEmpty()) {
			System.out.println(indent + "  <referencingDirectives>");
			for (XSDSchemaDirective xsdSchemaDirective : xsdSchema
					.getReferencingDirectives()) {
				XSDSchema referencingSchema = xsdSchemaDirective.getSchema();
				System.out.print(indent + "    ");
				printSchemaStart(referencingSchema);
				System.out.println();
				System.out.print(indent + "      ");
				if (xsdSchemaDirective instanceof XSDImport) {
					XSDImport xsdImport = (XSDImport) xsdSchemaDirective;
					System.out.print("<import namespace=\"");
					if (xsdImport.getNamespace() != null) {
						System.out.print(xsdImport.getNamespace());
					}
					System.out.print("\" schemaLocation=\"");
				} else if (xsdSchemaDirective instanceof XSDRedefine) {
					System.out.print("<redefine schemaLocation=\"");
				} else if (xsdSchemaDirective instanceof XSDInclude) {
					System.out.print("<include schemaLocation=\"");
				}
				if (xsdSchemaDirective.getSchemaLocation() != null) {
					System.out.print(xsdSchemaDirective.getSchemaLocation());
				}
				System.out.println("\"/>");
				System.out.println(indent + "    </schema>");
			}
			System.out.println(indent + "  </referencingDirectives>");
		}

		if (!xsdSchema.getIncorporatedVersions().isEmpty()) {
			System.out.println(indent + "  <incorporatedVersions>");
			for (XSDSchema incorporatedVersion : xsdSchema
					.getIncorporatedVersions()) {
				printDirectives(indent + "    ", incorporatedVersion);
			}
			System.out.println(indent + "  </incorporatedVersions>");
		}

		System.out.println(indent + "</schema>");
	}

}
时间: 2024-12-22 23:30:59

使用org.eclipse.xsd.XSDEnumerationFacet生成枚举类型的Schema的相关文章

打印org.eclipse.xsd.XSDSchema对象

因为网上关于Eclipse XSD的中文资料比较少,但是有的时候,我们需要使用Eclipse XSD的API去构造或者修改一个XSD文件. 那么当我们创建了org.eclipse.xsd.XSDSchema的对象,并已经在里面添加或者修改许多的元素类型等信息后,我们想知道我们的添加或者修改是否有效. 那么这个时候我们应该怎么办呢?有两种方式,我们把生成的org.eclipse.xsd.XSDSchema的对象,写到一个文件里面去,另外一种方式就是直接把XSDSchema对象 转成一个字符串,然后

巧用枚举类型,实现项目的多语言切换

在项目程序中实现多语言,有多种方式,而枚举类型的多语言处理,是比较头疼的问题.比如有下面这个枚举类型: public enum MySex { Women = 0, Man = 1 } 如果想在界面上输出这个枚举项,直接的做法如下处理: Console.WriteLine("Sex:{0},{1}",MySex.Women,MySex.Man); 程序输出: Sex:Women,Man 如果我们想输出枚举项的中文名称,怎么办呢? 通常的做法是这样: public enum MySex

Entity Framework 的枚举类型

新增数据模型,新增“实体”之后,新增“枚举类型”,创建Enum值,将“实体”中的列和Enum关联,选中“实体”中的列属性改变类型为Enum名称,生成数据库…… 如下转自:http://item.congci.com/item/entity-framework-meiju-leixing-enum 第一步:先创建一个实体对象,在VS 2012里面实体对象还可以修改实体颜色 第二步:对象已经有了,接着创建一个Type,Type为Enum,内部与外部(Internal and External),在空

Java的枚举类型

引用并转载于:http://blog.csdn.net/ishallwin/article/details/9440251 1.什么是枚举: 在实际编程中,往往存在着这样的“数据集”,它们的数值在程序中是稳定的,而且“数据集”中的元素是有限的. 例如:星期一到星期日七个数据元素组成了一周的“数据集”,春夏秋冬四个数据元素组成了四季的“数据集”. 在java中如何更好的使用这些“数据集”呢?因此枚举便派上了用场. 枚举是限定有限可能值的一种手段,使用枚举可以降低程序出错的几率,并可以提高代码的可读

C#的枚举数(Enumerator)和可枚举类型(Enumerable)

数组可以被foreach语句遍历数组中的元素,原因是数组可以按需提供一个叫做枚举数(enumerator)的对象.枚举数可以依次返回请求的数组的元素. 对于有枚举数的类型而言,必须有一个方法来获取它们.在.NET中获取一个对象枚举数的标准用法是调用对象的GetEnumerator方法.实现GetEnumerator方法的类型叫做可枚举类型(enumerable),数组就是可枚举类型. 要注意枚举数(enumerator)和可枚举类型(enumerable)的区别和联系. 枚举数是可以依次返回集合

比你想象中还要强大的枚举类型

开发中枚举类型往往被用在可以一一列举的实例中,比如 enum Color{red,green,blue;}.但是可能你不会注意到它的更强大之处,比如如下问题看看你能作答吗 1.枚举类型可以有构造函数吗? 2.枚举类型可以实现接口.继承类吗? 3.枚举类型可以有static成员变量和方法吗?以及可否有实例变量和方法吗? 4.枚举类型可以被继承吗? ..........等(打开eclipse一试便知的知识) 其实enum类型就是一个特殊的java类,它几乎具有一个java类所具有的大部分功能.它更类

Java数据类型在实际开发中的应用二枚举类型

在实际编程中,往往存在着这样的"数据集",它们的数值在程序中是稳定的,而且"数据集"中的元素是有限的.在JDK1.5之前,人们用接口来描述这一种数据类型. 1.5以后引入枚举 一:枚举类基本语法 定义: 创建枚举类型要使用 enum 关键字,如果是想声明简单枚举,属性之间用逗号相隔,如果是属性带id,类似(male(1))这种还需要一个带id的构造方法. 简单枚举类: public enum ColorEnum { red, green, yellow, blue;

asp.net MVC 枚举类型的处理的几种方式

1.基架自动生成@Html.EnumDropDownListFor()辅助方法映射到模型类属性的元数据. @model MajorConstruction.Models.Course <div class="form-group"> @Html.LabelFor(model => model.CourseType, htmlAttributes: new { @class = "control-label col-md-2" }) <div

Java魔法堂:枚举类型详解

一.前言 Java的枚举类型相对C#来说具有更灵活可配置性,Java的枚举类型可以携带更多的信息. // C# enum MyColor{ RED = 0, BLUE = 1 } Console.Write(MyColor.RED); // Java enum MyColor{ RED("Hot", 4), BLUE("SAD",8); private String mood; public String getMood{ return mood; } privat