/// <summary> /// TODO: Create new XmlSchema instead of DeepCopy /// </summary> /// <param name="templateSchema">Arbitrary maindoc schema used as a template for our new base class schema</param> /// <param name="sharedElementCount">Number of elements that shoud be copied over to the new base class schema complex type</param> /// <returns></returns> private static XmlSchema CreateAbstractBaseSchemaFromMaindocSchema(XmlSchema templateSchema, int sharedElementCount) { XmlSchema abstractBaseSchema = DeepCopy(templateSchema); var abstractBaseElement = abstractBaseSchema.Items.OfType<XmlSchemaElement>().Single(); // Single. There can only be one var abstractBaseComplexType = abstractBaseSchema.Items.OfType<XmlSchemaComplexType>().Single(); // Christopher Lambert again // overwrite template props abstractBaseSchema.TargetNamespace = abstractBaseSchema.TargetNamespace.Replace(abstractBaseElement.Name, Constants.abstractBaseSchemaName); abstractBaseSchema.Namespaces.Add("", abstractBaseSchema.TargetNamespace); abstractBaseSchema.SourceUri = templateSchema.SourceUri.Replace(abstractBaseElement.Name, Constants.abstractBaseSchemaName); abstractBaseComplexType.IsAbstract = true; abstractBaseComplexType.Annotation.Items.Clear(); XmlSchemaDocumentation doc = new XmlSchemaDocumentation(); var nodeCreaterDoc = new XmlDocument(); doc.Markup = new XmlNode[] { nodeCreaterDoc.CreateTextNode("This is a custom generated class that holds all the props/fields common to all UBL maindocs."), nodeCreaterDoc.CreateTextNode("You won't find a matching xsd file where it originates from.") }; abstractBaseComplexType.Annotation.Items.Add(doc); abstractBaseComplexType.Name = Constants.abstractBaseSchemaComplexTypeName; // remove non-shared tailing elements. XmlSchemaObjectCollection elementCollection = (abstractBaseComplexType.Particle as XmlSchemaSequence).Items; while (sharedElementCount < elementCollection.Count) elementCollection.RemoveAt(sharedElementCount); abstractBaseElement.Name = Constants.abstarctBaseSchemaElementName; abstractBaseElement.SchemaTypeName = new XmlQualifiedName(Constants.abstractBaseSchemaComplexTypeName, abstractBaseSchema.TargetNamespace); // Don't need schemaLocation for loaded schemas. Will generate schemasetcompile warnings if not removed foreach (var baseSchemaImports in abstractBaseSchema.Includes.OfType<XmlSchemaImport>()) baseSchemaImports.SchemaLocation = null; return abstractBaseSchema; }
private static string CleanAnnotation(XmlSchemaDocumentation item) { var text = ""; if(item.Markup[0].InnerText.Substring(0,1).Contains("\n")) { text = item.Markup[0].InnerText.Remove(0, 2); } else { text = item.Markup[0].InnerText; } text = text.Replace("\n ", " "); text = text.Replace("\n ", " "); text = text.Replace("\n ", " "); text = text.Replace("\n ", " "); text = text.Replace("\n ", " "); text = text.Replace("\n ", " "); text = text.Replace("\n ", " "); text = text.Replace("\n ", " "); text = text.Replace("\n ", " "); text = text.Replace("\n ", " "); text = text.Replace("\n ", " "); text = text.Replace("\n ", " "); text = text.Replace("\n ", " "); text = text.Replace("\n ", " "); text = text.Replace("\n ", " "); text = text.Replace("\n ", " "); text = text.Replace("\n ", " "); text = text.Replace("\n ", " "); text = text.Replace("\n", " ").Trim(); text = text.Replace("'", "''"); text = text.Replace("\t",""); return text; }
//<documentation // source = anyURI // xml:lang = language> // Content: ({any})* //</documentation> internal static XmlSchemaDocumentation Read(XmlSchemaReader reader, ValidationEventHandler h, out bool skip) { skip = false; XmlSchemaDocumentation doc = new XmlSchemaDocumentation(); reader.MoveToElement(); if(reader.NamespaceURI != XmlSchema.Namespace || reader.LocalName != "documentation") { error(h,"Should not happen :1: XmlSchemaDocumentation.Read, name="+reader.Name,null); reader.Skip(); return null; } doc.LineNumber = reader.LineNumber; doc.LinePosition = reader.LinePosition; doc.SourceUri = reader.BaseURI; while(reader.MoveToNextAttribute()) { if(reader.Name == "source") { doc.source = reader.Value; } else if(reader.Name == "xml:lang") { doc.language = reader.Value; } else { error(h,reader.Name + " is not a valid attribute for documentation",null); } } reader.MoveToElement(); if(reader.IsEmptyElement) { doc.Markup = new XmlNode[0]; return doc; } //Content {any}* XmlDocument xmldoc = new XmlDocument(); xmldoc.AppendChild(xmldoc.ReadNode(reader)); XmlNode root = xmldoc.FirstChild; if(root != null && root.ChildNodes != null) { doc.Markup = new XmlNode[root.ChildNodes.Count]; for(int i=0;i<root.ChildNodes.Count;i++) { doc.Markup[i] = root.ChildNodes[i]; } } if(reader.NodeType == XmlNodeType.Element || reader.NodeType == XmlNodeType.EndElement) skip = true; return doc; }
internal static XmlSchemaDocumentation Read(XmlSchemaReader reader, ValidationEventHandler h, out bool skip) { skip = false; XmlSchemaDocumentation xmlSchemaDocumentation = new XmlSchemaDocumentation(); reader.MoveToElement(); if (reader.NamespaceURI != "http://www.w3.org/2001/XMLSchema" || reader.LocalName != "documentation") { XmlSchemaObject.error(h, "Should not happen :1: XmlSchemaDocumentation.Read, name=" + reader.Name, null); reader.Skip(); return(null); } xmlSchemaDocumentation.LineNumber = reader.LineNumber; xmlSchemaDocumentation.LinePosition = reader.LinePosition; xmlSchemaDocumentation.SourceUri = reader.BaseURI; while (reader.MoveToNextAttribute()) { if (reader.Name == "source") { xmlSchemaDocumentation.source = reader.Value; } else if (reader.Name == "xml:lang") { xmlSchemaDocumentation.language = reader.Value; } else { XmlSchemaObject.error(h, reader.Name + " is not a valid attribute for documentation", null); } } reader.MoveToElement(); if (reader.IsEmptyElement) { xmlSchemaDocumentation.Markup = new XmlNode[0]; return(xmlSchemaDocumentation); } XmlDocument xmlDocument = new XmlDocument(); xmlDocument.AppendChild(xmlDocument.ReadNode(reader)); XmlNode firstChild = xmlDocument.FirstChild; if (firstChild != null && firstChild.ChildNodes != null) { xmlSchemaDocumentation.Markup = new XmlNode[firstChild.ChildNodes.Count]; for (int i = 0; i < firstChild.ChildNodes.Count; i++) { xmlSchemaDocumentation.Markup[i] = firstChild.ChildNodes[i]; } } if (reader.NodeType == XmlNodeType.Element || reader.NodeType == XmlNodeType.EndElement) { skip = true; } return(xmlSchemaDocumentation); }
public XmlSchema GetDataSchemas(XmlSchema querySchema,IEnumerable<Registration> registrations) { var schema = new XmlSchema { TargetNamespace = RegistrationStorage.Dataspace }; schema.Namespaces.Add("", RegistrationStorage.Dataspace); var guid = CreateGuidType(); schema.Items.Add(guid); schema.Includes.Add(new XmlSchemaImport { Schema = querySchema, Namespace = querySchema.TargetNamespace }); foreach (var registration in registrations) { var etype = new XmlSchemaComplexType { Name = registration.ResourceName, Annotation = new XmlSchemaAnnotation() }; var doc = new XmlSchemaDocumentation { Markup = TextToNode(registration.ResourceType.FullName) }; etype.Annotation.Items.Add(doc); etype.Block = XmlSchemaDerivationMethod.Extension; var idAttr = new XmlSchemaAttribute { Name = "Id", SchemaTypeName = new XmlQualifiedName(guid.Name, RegistrationStorage.Dataspace), Use = XmlSchemaUse.Required }; etype.Attributes.Add(idAttr); var noChildrenAttr = new XmlSchemaAttribute { Name = RegistrationStorage.DefinitlyNoChildren, SchemaType = XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Boolean), Use = XmlSchemaUse.Optional }; etype.Attributes.Add(noChildrenAttr); if (querySchema.Items.OfType<XmlSchemaAttributeGroup>().Any(k => k.Name == etype.Name)) { var group = new XmlSchemaAttributeGroupRef(); group.RefName = new XmlQualifiedName(etype.Name.Replace(" ", "_"), querySchema.TargetNamespace); etype.Attributes.Add(group); } schema.Items.Add(etype); } return schema; }
/// <summary> /// Creates a new instance of the <see cref="NAntSchemaGenerator" /> /// class. /// </summary> /// <param name="tasks">Tasks for which a schema should be generated.</param> /// <param name="dataTypes">Data Types for which a schema should be generated.</param> /// <param name="targetNS">The namespace to use. /// <example> http://tempuri.org/nant.xsd </example> /// </param> public NAntSchemaGenerator(Type[] tasks, Type[] dataTypes, string targetNS) { //setup namespace stuff if (targetNS != null) { _nantSchema.TargetNamespace = targetNS; _nantSchema.Namespaces.Add("nant", _nantSchema.TargetNamespace); } // add XSD namespace so that all xsd elements are prefix'd _nantSchema.Namespaces.Add("xs", XmlSchema.Namespace); _nantSchema.ElementFormDefault = XmlSchemaForm.Qualified; // initialize stuff _nantComplexTypes = new HybridDictionary(tasks.Length + dataTypes.Length); XmlSchemaAnnotation schemaAnnotation = new XmlSchemaAnnotation(); XmlSchemaDocumentation schemaDocumentation = new XmlSchemaDocumentation(); string doc = String.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("String_SchemaGenerated"), DateTime.Now); schemaDocumentation.Markup = TextToNodeArray(doc); schemaAnnotation.Items.Add(schemaDocumentation); _nantSchema.Items.Add(schemaAnnotation); // create temp list of taskcontainer Complex Types ArrayList taskContainerComplexTypes = new ArrayList(4); XmlSchemaComplexType containerCT = FindOrCreateComplexType(typeof(TaskContainer)); if (containerCT.Particle == null) { // just create empty sequence to which elements will // be added later containerCT.Particle = CreateXsdSequence(0, Decimal.MaxValue); } taskContainerComplexTypes.Add(containerCT); // create temp list of task Complex Types ArrayList dataTypeComplexTypes = new ArrayList(dataTypes.Length); foreach (Type t in dataTypes) { dataTypeComplexTypes.Add(FindOrCreateComplexType(t)); } foreach (Type t in tasks) { XmlSchemaComplexType taskCT = FindOrCreateComplexType(t); // allow any tasks... if (t.IsSubclassOf(typeof(TaskContainer))) { taskContainerComplexTypes.Add(taskCT); } } Compile(); // update the taskcontainerCTs to allow any other task and the // list of tasks generated foreach(XmlSchemaComplexType ct in taskContainerComplexTypes) { XmlSchemaSequence seq = ct.Particle as XmlSchemaSequence; if (seq != null) { seq.Items.Add(CreateTaskListComplexType(tasks).Particle); } else { logger.Error("Unable to fixup complextype with children. Particle is not XmlSchemaSequence"); } } Compile(); // create target ComplexType _targetCT = CreateTaskListComplexType(tasks, dataTypes, false); _targetCT.Name = "Target"; // This is a response to Bug#: 3058913. If not considered neccessary, remove line below. _targetCT.IsMixed = true; // name attribute _targetCT.Attributes.Add(CreateXsdAttribute("name", true)); // depends attribute _targetCT.Attributes.Add(CreateXsdAttribute("depends", false)); // description attribute _targetCT.Attributes.Add(CreateXsdAttribute("description", false)); // if attribute _targetCT.Attributes.Add(CreateXsdAttribute("if", false)); // unless attribute _targetCT.Attributes.Add(CreateXsdAttribute("unless", false)); _nantSchema.Items.Add(_targetCT); Compile(); // Generate project Element and ComplexType XmlSchemaElement projectElement = new XmlSchemaElement(); projectElement.Name = "project"; XmlSchemaComplexType projectCT = CreateTaskListComplexType(tasks, dataTypes, true); projectElement.SchemaType = projectCT; //name attribute projectCT.Attributes.Add(CreateXsdAttribute("name", true)); //default attribute projectCT.Attributes.Add(CreateXsdAttribute("default", false)); //basedir attribute projectCT.Attributes.Add(CreateXsdAttribute("basedir", false)); _nantSchema.Items.Add(projectElement); Compile(); }
private static XmlSchemaDocumentation CreateDocumentationItem(string text) { XmlDocument doc = new XmlDocument(); XmlSchemaDocumentation comment = new XmlSchemaDocumentation(); XmlNode node = doc.CreateTextNode(text); comment.Markup = new XmlNode[] { node }; return comment; }
private static string ProcessDocumentation(XmlSchemaDocumentation schemaDocumentation) { StringBuilder result = new StringBuilder(); if (schemaDocumentation == null) return result.ToString(); foreach(XmlNode node in schemaDocumentation.Markup) { result.AppendLine(node.InnerText.Trim()); } return result.ToString(); }
internal static XmlSchemaAnnotation Read(XmlSchemaReader reader, ValidationEventHandler h) { XmlSchemaAnnotation xmlSchemaAnnotation = new XmlSchemaAnnotation(); reader.MoveToElement(); if (reader.NamespaceURI != "http://www.w3.org/2001/XMLSchema" || reader.LocalName != "annotation") { XmlSchemaObject.error(h, "Should not happen :1: XmlSchemaAnnotation.Read, name=" + reader.Name, null); reader.SkipToEnd(); return(null); } xmlSchemaAnnotation.LineNumber = reader.LineNumber; xmlSchemaAnnotation.LinePosition = reader.LinePosition; xmlSchemaAnnotation.SourceUri = reader.BaseURI; while (reader.MoveToNextAttribute()) { if (reader.Name == "id") { xmlSchemaAnnotation.Id = reader.Value; } else if ((reader.NamespaceURI == string.Empty && reader.Name != "xmlns") || reader.NamespaceURI == "http://www.w3.org/2001/XMLSchema") { XmlSchemaObject.error(h, reader.Name + " is not a valid attribute for annotation", null); } else { XmlSchemaUtil.ReadUnhandledAttribute(reader, xmlSchemaAnnotation); } } reader.MoveToElement(); if (reader.IsEmptyElement) { return(xmlSchemaAnnotation); } bool flag = false; string text = null; while (!reader.EOF) { if (flag) { flag = false; } else { reader.ReadNextElement(); } if (reader.NodeType == XmlNodeType.EndElement) { bool flag2 = true; string text2 = "annotation"; if (text != null) { text2 = text; text = null; flag2 = false; } if (reader.LocalName != text2) { XmlSchemaObject.error(h, "Should not happen :2: XmlSchemaAnnotation.Read, name=" + reader.Name + ",expected=" + text2, null); } if (flag2) { break; } } else if (reader.LocalName == "appinfo") { XmlSchemaAppInfo xmlSchemaAppInfo = XmlSchemaAppInfo.Read(reader, h, out flag); if (xmlSchemaAppInfo != null) { xmlSchemaAnnotation.items.Add(xmlSchemaAppInfo); } } else if (reader.LocalName == "documentation") { XmlSchemaDocumentation xmlSchemaDocumentation = XmlSchemaDocumentation.Read(reader, h, out flag); if (xmlSchemaDocumentation != null) { xmlSchemaAnnotation.items.Add(xmlSchemaDocumentation); } } else { reader.RaiseInvalidElementError(); } } return(xmlSchemaAnnotation); }
private void Write9_XmlSchemaDocumentation(string n, string ns, XmlSchemaDocumentation o, bool isNullable, bool needType) { if (o == null) { if (isNullable) { base.WriteNullTagLiteral(n, ns); } } else { if (!needType && !(o.GetType() == typeof(XmlSchemaDocumentation))) { throw base.CreateUnknownTypeException(o); } base.EscapeName = false; base.WriteStartElement(n, ns, o, false, o.Namespaces); if (needType) { base.WriteXsiType("XmlSchemaDocumentation", "http://www.w3.org/2001/XMLSchema"); } base.WriteAttribute("source", "", o.Source); base.WriteAttribute("lang", "http://www.w3.org/XML/1998/namespace", o.Language); XmlNode[] markup = o.Markup; if (markup != null) { for (int i = 0; i < markup.Length; i++) { XmlNode node = markup[i]; if (node is XmlElement) { XmlElement element = (XmlElement) node; if ((element == null) && (element != null)) { throw base.CreateInvalidAnyTypeException(element); } base.WriteElementLiteral(element, "", null, false, true); } else if (node != null) { node.WriteTo(base.Writer); } else if (node != null) { throw base.CreateUnknownTypeException(node); } } } base.WriteEndElement(o); } }
void Write6_XmlSchemaDocumentation(XmlSchemaDocumentation o) { if ((object)o == null) return; WriteStartElement("documentation"); WriteAttribute(@"source", @"", ((System.String)o.@Source)); WriteAttribute(@"lang", @"http://www.w3.org/XML/1998/namespace", ((System.String)o.@Language)); XmlNode[] a = (XmlNode[])o.@Markup; if (a != null) { for (int ia = 0; ia < a.Length; ia++) { XmlNode ai = (XmlNode)a[ia]; WriteStartElement("node"); WriteAttribute("xml", "", ai.OuterXml); } } WriteEndElement(); }
/// <summary> /// Generate the complex type /// </summary> /// <param name="cls">The class to generate the complex type for</param> /// <param name="prefix">The prefix namespace for the class</param> /// <param name="genericParameters">Generic parameters</param> private XmlSchemaComplexType GenerateComplexType(Class cls, string prefix, List<TypeReference> genericParameters, List<String> includedModels, List<TypeReference> additionalCompileTargets) { if (cls != null && genericParameters != null && cls.TypeParameters != null && cls.TypeParameters.Count != genericParameters.Count) return null; if (cls == null) { Trace.WriteLine("Cannot generate complex type for null class", "error"); return null; } // Create the complex type XmlSchemaComplexType complexType = new XmlSchemaComplexType() { Name = prefix != null ? String.Format("{0}.{1}.{2}", prefix, cls.ContainerName, cls.Name) : String.Format("{0}.{1}", cls.ContainerName, cls.Name), IsAbstract = cls.IsAbstract }; // Populate documentation for the type if (!Documentation.IsEmpty(cls.Documentation)) { XmlSchemaDocumentation documentation = new XmlSchemaDocumentation(); XmlDocument documentationMarkup = new XmlDocument(); documentationMarkup.LoadXml("<div xmlns=\"http://www.w3.org/1999/xhtml\">" + cls.Documentation.ToString() + "</div>"); documentation.Markup = new List<XmlNode>(documentationMarkup.ChildNodes.Cast<XmlNode>()).ToArray(); complexType.Annotation = new XmlSchemaAnnotation(); complexType.Annotation.Items.Add(documentation); } // Complex Content XmlSchemaComplexContentExtension content = new XmlSchemaComplexContentExtension(); // Null flavors and stuff if (cls.BaseClass != null) { // Add the import for model if (!includedModels.Contains(cls.BaseClass.Class.ContainerName)) includedModels.Add(cls.BaseClass.Class.ContainerName); // Set the extension content.BaseTypeName = new XmlQualifiedName(cls.BaseClass.Name, targetNs); } else if(cls.CreateTypeReference().Name != baseClass) content.BaseTypeName = new XmlQualifiedName(baseClass, targetNs); // Sequence XmlSchemaSequence sequence = new XmlSchemaSequence(); // Iterate through content foreach (ClassContent cc in cls.Content) { if (cc is Property) { Property property = cc as Property; TypeReference realReference = property.Type.Class == null && genericParameters != null ? genericParameters.Find(o => o is TypeParameter && (o as TypeParameter).ParameterName == property.Type.Name) : property.Type; // Is this a property that really represents a choice? // This sometimes happens when a property (namely ACT) points to an // abstract class that has many different sub-traversals... if (realReference != null && realReference.Class != null && realReference.Class.IsAbstract) // Choice { XmlSchemaChoice propertyChoice = new XmlSchemaChoice() { MinOccursString = property.MinOccurs, MaxOccursString = property.MaxOccurs == "*" ? "unbounded" : property.MaxOccurs }; List<XmlSchemaElement> elements = CreateChoice(property, realReference.Class, genericParameters, prefix, includedModels, additionalCompileTargets); foreach (XmlSchemaElement ele in elements) propertyChoice.Items.Add(ele); sequence.Items.Add(propertyChoice); } else // The property is really a property switch (property.PropertyType) { case Property.PropertyTypes.Structural: content.Attributes.Add(CreateAttribute(property)); break; default: sequence.Items.Add(CreateElement(property, genericParameters, prefix, includedModels, additionalCompileTargets)); break; } } else if (cc is Choice) { // Render the choice XmlSchemaChoice choice = new XmlSchemaChoice() { MinOccursString = cc.MinOccurs, MaxOccursString = cc.MaxOccurs == "*" ? "unbounded" : cc.MaxOccurs }; List<XmlSchemaElement> elements = CreateChoice(cc as Choice, genericParameters, prefix, includedModels, additionalCompileTargets); foreach (XmlSchemaElement element in elements) choice.Items.Add(element); sequence.Items.Add(choice); } } // Now for the inherited classes, these could also be sent if (cls.SpecializedBy.Count > 0) { XmlSchemaChoice childChoice = new XmlSchemaChoice(); //// Generate a choice for all child elements //List<XmlSchemaElement> elements = GenerateChildChoices(cls, genericParameters, prefix, includedModels, additionalCompileTargets); //foreach (XmlSchemaElement ele in elements) // childChoice.Items.Add(ele); } content.Particle = sequence; // Sequence // Add the sequence to the content if (sequence.Items.Count > 0) { if (content.BaseTypeName != null && !String.IsNullOrEmpty(content.BaseTypeName.Name)) complexType.ContentModel = new XmlSchemaComplexContent() { Content = content }; else complexType.Particle = sequence; } return complexType; }
protected virtual void Visit(XmlSchemaDocumentation documentation) { }
//<annotation // id = ID // {any attributes with non-schema namespace . . .}> // Content: (appinfo | documentation)* //</annotation> internal static XmlSchemaAnnotation Read(XmlSchemaReader reader, ValidationEventHandler h) { XmlSchemaAnnotation annotation = new XmlSchemaAnnotation(); reader.MoveToElement(); if (reader.NamespaceURI != XmlSchema.Namespace || reader.LocalName != xmlname) { error(h, "Should not happen :1: XmlSchemaAnnotation.Read, name=" + reader.Name, null); reader.SkipToEnd(); return(null); } annotation.LineNumber = reader.LineNumber; annotation.LinePosition = reader.LinePosition; annotation.SourceUri = reader.BaseURI; //Read Attributes while (reader.MoveToNextAttribute()) { if (reader.Name == "id") { annotation.Id = reader.Value; } else if ((reader.NamespaceURI == "" && reader.Name != "xmlns") || reader.NamespaceURI == XmlSchema.Namespace) { error(h, reader.Name + " is not a valid attribute for annotation", null); } else { XmlSchemaUtil.ReadUnhandledAttribute(reader, annotation); } } reader.MoveToElement(); if (reader.IsEmptyElement) { return(annotation); } //Content: (appinfo | documentation)* bool skip = false; string expectedEnd = null; while (!reader.EOF) { if (skip) { skip = false; } else { reader.ReadNextElement(); } if (reader.NodeType == XmlNodeType.EndElement) { bool end = true; string expected = xmlname; if (expectedEnd != null) { expected = expectedEnd; expectedEnd = null; end = false; } if (reader.LocalName != expected) { error(h, "Should not happen :2: XmlSchemaAnnotation.Read, name=" + reader.Name + ",expected=" + expected, null); } if (end) { break; } else { continue; } } if (reader.LocalName == "appinfo") { XmlSchemaAppInfo appinfo = XmlSchemaAppInfo.Read(reader, h, out skip); if (appinfo != null) { annotation.items.Add(appinfo); } continue; } if (reader.LocalName == "documentation") { XmlSchemaDocumentation documentation = XmlSchemaDocumentation.Read(reader, h, out skip); if (documentation != null) { annotation.items.Add(documentation); } continue; } reader.RaiseInvalidElementError(); } return(annotation); }
/// <summary> /// Generate the VOC.xsd file /// </summary> private void GenerateVocabulary() { System.Diagnostics.Trace.WriteLine("Generating VOC.XSD...", "debug"); ClassRepository classRep = hostContext.Data["SourceCR"] as ClassRepository; // Enumerations var enumerations = from clsRep in classRep where clsRep.Value is Enumeration && (clsRep.Value as Enumeration).Literals.Count > 0 select clsRep.Value as Enumeration; XmlSchema schema = new XmlSchema(); //schema.TargetNamespace = targetNs; // Enumerations foreach (var eType in enumerations) { #region Check for members bool used = false; // Does this enumeration have any references? foreach (KeyValuePair<String, Feature> kv in eType.MemberOf) if (kv.Value is Class) foreach (ClassContent cc in (kv.Value as Class).Content) used |= cc is Property && (cc as Property).SupplierDomain == eType; #endregion Check for Members // Is this enumeration used? if (used) { // Generate the type XmlSchemaSimpleType enumerationType = new XmlSchemaSimpleType(); enumerationType.Name = eType.Name; // Populate documentation if (!Documentation.IsEmpty(eType.Documentation)) { XmlSchemaDocumentation documentation = new XmlSchemaDocumentation(); XmlDocument documentationMarkup = new XmlDocument(); documentationMarkup.LoadXml("<div xmlns=\"http://www.w3.org/1999/xhtml\">" + eType.Documentation.ToString() + "</div>"); documentation.Markup = new List<XmlNode>(documentationMarkup.ChildNodes.Cast<XmlNode>()).ToArray(); enumerationType.Annotation = new XmlSchemaAnnotation(); enumerationType.Annotation.Items.Add(documentation); } // Populate the simple type XmlSchemaSimpleTypeRestriction restriction = new XmlSchemaSimpleTypeRestriction() { BaseTypeName = new XmlQualifiedName("token", "http://www.w3.org/2001/XMLSchema") }; // Create the restriction facets foreach (var literal in eType.Literals) { XmlSchemaEnumerationFacet facet = new XmlSchemaEnumerationFacet() { Value = literal.Name }; // Populate documentation if (!Documentation.IsEmpty(literal.Documentation)) { try { XmlSchemaDocumentation facetDocumentation = new XmlSchemaDocumentation(); XmlDocument facetDocumentationMarkup = new XmlDocument(); facetDocumentationMarkup.LoadXml("<div xmlns=\"http://www.w3.org/1999/xhtml\">" + literal.Documentation.ToString() + "</div>"); facetDocumentation.Markup = new List<XmlNode>(facetDocumentationMarkup.ChildNodes.Cast<XmlNode>()).ToArray(); facet.Annotation = new XmlSchemaAnnotation(); facet.Annotation.Items.Add(facetDocumentation); } catch (Exception e) { if (hostContext.Mode == Pipeline.OperationModeType.Quirks) System.Diagnostics.Trace.WriteLine(String.Format("error {0} is being ignored", e.Message), "quirks"); else throw; } } restriction.Facets.Add(facet); } enumerationType.Content = restriction; // Now, add the type to the schema schema.Items.Add(enumerationType); } } TextWriter tw = null; try { tw = File.CreateText(Path.Combine(outputDir, "voc.xsd")); schema.Write(tw); } catch (Exception e) { System.Diagnostics.Debug.WriteLine(e.Message, "error"); } finally { if (tw != null) tw.Close(); } }
/// <summary> /// Parse <paramref name="property"/> and create an XmlSchemaObject for it /// </summary> private XmlSchemaAttribute CreateAttribute(Property property) { // property data type must be a data type if (property.Type.CoreDatatypeName == null) { System.Diagnostics.Trace.WriteLine(string.Format("Can't bind complex type '{0}' to attribute '{1}'.", property.Type.Name, property.Name), "warn"); return null; } // Return value XmlSchemaAttribute retVal = new XmlSchemaAttribute() { Name = property.Name, Use = property.MaxOccurs == "0" ? XmlSchemaUse.Prohibited : property.MinOccurs != "0" ? XmlSchemaUse.Required : XmlSchemaUse.Optional }; // Fixed value if (property.FixedValue != null) retVal.FixedValue = property.FixedValue; // Is this bound to a vocab realm? if (property.SupplierDomain != null && property.SupplierStrength == Property.CodingStrengthKind.CodedNoExtensions) // Generate the type as a ref to the voc realm retVal.SchemaTypeName = new XmlQualifiedName(property.SupplierDomain.Name, targetNs); else { var dataType = dataTypes.Find(o => o.Name == property.Type.CoreDatatypeName.ToLower()); if (dataType == null) { System.Diagnostics.Trace.WriteLine(String.Format("Can't find data type '{0}' in the file '{1}'. Using xs:token...", property.Type.CoreDatatypeName, dataTypesXsd), "warn"); retVal.SchemaTypeName = new XmlQualifiedName("token", "http://www.w3.org/2001/XMLSchema"); } else retVal.SchemaTypeName = new XmlQualifiedName(dataType.Name, dataType.Namespace); } // Generate property documentation if (!Documentation.IsEmpty(property.Documentation)) { XmlSchemaDocumentation documentation = new XmlSchemaDocumentation(); XmlDocument documentationMarkup = new XmlDocument(); documentationMarkup.LoadXml("<div xmlns=\"http://www.w3.org/1999/xhtml\">" + property.Documentation.ToString() + "</div>"); documentation.Markup = new List<XmlNode>(documentationMarkup.ChildNodes.Cast<XmlNode>()).ToArray(); retVal.Annotation = new XmlSchemaAnnotation(); retVal.Annotation.Items.Add(documentation); } // Return the retVal return retVal; }
/// <summary> /// Create an element /// </summary> private XmlSchemaElement CreateElement(Property property, List<TypeReference> genericParameters, string prefix, List<String> includedModels, List<TypeReference> additionalCompileTargets) { // Return value XmlSchemaElement retVal = new XmlSchemaElement() { Name = property.Name, MaxOccursString = property.MaxOccurs == "*" ? "unbounded" : property.MaxOccurs, MinOccursString = property.MinOccurs }; TypeReference propertyType = property.Type; List<String> collectionTypes = new List<string>() { "LIST","SET","DSET","BAG" }; // Is the property type a collection if (property.MaxOccurs != "0" && collectionTypes.Contains(propertyType.CoreDatatypeName) && propertyType.GenericSupplier != null && propertyType.GenericSupplier.Count >0) propertyType = propertyType.GenericSupplier[0]; // It is, so we replace with the inner // Add appinfo for the collapsing needed if (property.Annotations != null && property.Annotations.Count > 0) { if (retVal.Annotation == null) retVal.Annotation = new XmlSchemaAnnotation(); XmlSchemaAppInfo appInfo = new XmlSchemaAppInfo(); XmlDocument appInfoDocument = new XmlDocument(); appInfoDocument.AppendChild(appInfoDocument.CreateElement("annotations","http://marc.mohawkcollege.ca/hi")); foreach (Annotation annot in property.Annotations) { XmlNode node = appInfoDocument.DocumentElement.AppendChild(appInfoDocument.CreateElement(annot.GetType().Name, "http://marc.mohawkcollege.ca/hi")); node.InnerText = annot.ToString(); } appInfo.Markup = new XmlNode[] { appInfoDocument.DocumentElement }; retVal.Annotation.Items.Add(appInfo); } // Generate the generic type parameter that has been bound upstream? if (property.Container is Class && (property.Container as Class).TypeParameters != null && property.Type.Name != null && (property.Container as Class).TypeParameters.Find(o => o.ParameterName == property.Type.Name) != null) { // Get the current type Class containerClass = property.Container as Class; // Determine the type order of the generic parameter int order = containerClass.TypeParameters.FindIndex(o => o.ParameterName == property.Type.CoreDatatypeName); // Alternative traversal name usually happens on a generic if (property.AlternateTraversalNames != null && property.AlternateTraversalNames.Count > 0) { MohawkCollege.EHR.gpmr.COR.Property.AlternateTraversalData name = property.AlternateTraversalNames.Find(o => o.CaseWhen.Name == genericParameters[order].Name && (o.InteractionOwner.Name == prefix || prefix==null)); if (name.TraversalName != null) retVal.Name = name.TraversalName; } // Now set the reference to the generated type if (prefix != null && genericParameters != null && genericParameters[order].GenericSupplier != null && genericParameters[order].GenericSupplier.Count > 0) // Prefix is here retVal.SchemaTypeName = new XmlQualifiedName(String.Format("{0}.{1}", prefix, genericParameters[order].Name), targetNs); else if(genericParameters != null) { // TODO: Validate this works if (includedModels != null && genericParameters[order].Class != null && !includedModels.Contains(genericParameters[order].Class.ContainerName)) includedModels.Add(genericParameters[order].Class.ContainerName); retVal.SchemaTypeName = new XmlQualifiedName(genericParameters[order].Name, targetNs); } else Trace.WriteLine(String.Format("Generic parameters are not specified '{0}'...", property.Name), "error"); } else if (property.Type.Class != null && property.Type.GenericSupplier != null && property.Type.GenericSupplier.Count > 0) // Other Generic { // Add this to the list of types that need to be generated additionalCompileTargets.Add(property.Type); // Now set the reference if (prefix != null) // Prefix is here retVal.SchemaTypeName = new XmlQualifiedName(String.Format("{0}.{1}", prefix, property.Type.Name), targetNs); else { // TODO: Validate this works if (!includedModels.Contains(property.Type.Class.ContainerName)) includedModels.Add(property.Type.Class.ContainerName); retVal.SchemaTypeName = new XmlQualifiedName(property.Type.Class.ContainerName, targetNs); } } else if (property.Type.Class != null) // Complex association { // Attempt to bind to the class // Genericized type reference, so we need to generate a new type reference if (property.Type.GenericSupplier != null && property.Type.GenericSupplier.Count > 0) ;//TODO: Generate a new type here else { if (!includedModels.Contains(property.Type.Class.ContainerName)) includedModels.Add(property.Type.Class.ContainerName); retVal.SchemaTypeName = new XmlQualifiedName(property.Type.Name, targetNs); } } else if (propertyType.CoreDatatypeName != null) // Data Type { var dataType = dataTypes.Find(o => o.Name == MakeSchemaFriendlyCoreType(propertyType)); if (dataType == null) { System.Diagnostics.Trace.WriteLine(String.Format("Can't find data type '{0}' in the file '{1}'. Using xs:any...", propertyType.CoreDatatypeName, dataTypesXsd), "warn"); retVal.SchemaTypeName = new XmlQualifiedName("anyType", "http://www.w3.org/2001/XMLSchema"); } else retVal.SchemaTypeName = new XmlQualifiedName(dataType.Name, dataType.Namespace); } else System.Diagnostics.Trace.WriteLine(String.Format("Can't bind type '{0}' to element '{1}'. Can't determine type family.", property.Type.Name, property.Name), "warn"); // Generate property documentation if (!Documentation.IsEmpty(property.Documentation)) { if(retVal.Annotation == null) retVal.Annotation = new XmlSchemaAnnotation(); XmlSchemaDocumentation documentation = new XmlSchemaDocumentation(); XmlDocument documentationMarkup = new XmlDocument(); documentationMarkup.LoadXml("<div xmlns=\"http://www.w3.org/1999/xhtml\">" + property.Documentation.ToString() + "</div>"); documentation.Markup = new List<XmlNode>(documentationMarkup.ChildNodes.Cast<XmlNode>()).ToArray(); retVal.Annotation.Items.Add(documentation); } return retVal; }
protected XmlSchemaComplexType FindOrCreateComplexType(Type t) { XmlSchemaComplexType ct; string typeId = GenerateIDFromType(t); ct = FindComplexTypeByID(typeId); if (ct != null) { return ct; } ct = new XmlSchemaComplexType(); ct.Name = typeId; // Force mixed attribute for tasks names in the mixedTaskNames array. Fixes Bug#: 3058913 if (Array.IndexOf(mixedTaskNames, ct.Name) != -1) { ct.IsMixed = true; } // add complex type to collection immediately to avoid stack // overflows, when we allow a type to be nested _nantComplexTypes.Add(typeId, ct); #if NOT_IMPLEMENTED // // TODO - add task/type documentation in the future // ct.Annotation = new XmlSchemaAnnotation(); XmlSchemaDocumentation doc = new XmlSchemaDocumentation(); ct.Annotation.Items.Add(doc); doc.Markup = ...; #endif XmlSchemaSequence group1 = null; XmlSchemaObjectCollection attributesCollection = ct.Attributes; foreach (MemberInfo memInfo in t.GetMembers(BindingFlags.Instance | BindingFlags.Public)) { if (memInfo.DeclaringType.Equals(typeof(object))) { continue; } //Check for any return type that is derived from Element // add Attributes TaskAttributeAttribute taskAttrAttr = (TaskAttributeAttribute) Attribute.GetCustomAttribute(memInfo, typeof(TaskAttributeAttribute), false); BuildElementAttribute buildElemAttr = (BuildElementAttribute) Attribute.GetCustomAttribute(memInfo, typeof(BuildElementAttribute), false); if (taskAttrAttr != null) { XmlSchemaAttribute newAttr = CreateXsdAttribute(taskAttrAttr.Name, taskAttrAttr.Required); attributesCollection.Add(newAttr); } else if (buildElemAttr != null) { // Create individial choice for any individual child Element Decimal min = 0; if (buildElemAttr.Required) { min = 1; } XmlSchemaElement childElement = new XmlSchemaElement(); childElement.MinOccurs = min; childElement.MaxOccurs = 1; childElement.Name = buildElemAttr.Name; //XmlSchemaGroupBase elementGroup = CreateXsdSequence(min, Decimal.MaxValue); Type childType; // We will only process child elements if they are defined for Properties or Fields, this should be enforced by the AttributeUsage on the Attribute class if (memInfo is PropertyInfo) { childType = ((PropertyInfo) memInfo).PropertyType; } else if (memInfo is FieldInfo) { childType = ((FieldInfo) memInfo).FieldType; } else if (memInfo is MethodInfo) { MethodInfo method = (MethodInfo) memInfo; if (method.GetParameters().Length == 1) { childType = method.GetParameters()[0].ParameterType; } else { throw new ApplicationException("Method should have one parameter."); } } else { throw new ApplicationException("Member Type != Field/Property/Method"); } BuildElementArrayAttribute buildElementArrayAttribute = (BuildElementArrayAttribute) Attribute.GetCustomAttribute(memInfo, typeof(BuildElementArrayAttribute), false); // determine type of child elements if (buildElementArrayAttribute != null) { if (buildElementArrayAttribute.ElementType == null) { if (childType.IsArray) { childType = childType.GetElementType(); } else { Type elementType = null; // locate Add method with 1 parameter, type of that parameter is parameter type foreach (MethodInfo method in childType.GetMethods(BindingFlags.Public | BindingFlags.Instance)) { if (method.Name == "Add" && method.GetParameters().Length == 1) { ParameterInfo parameter = method.GetParameters()[0]; elementType = parameter.ParameterType; break; } } childType = elementType; } } else { childType = buildElementArrayAttribute.ElementType; } if (childType == null || !typeof(Element).IsAssignableFrom(childType)) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1140"), memInfo.DeclaringType.FullName, memInfo.Name)); } } BuildElementCollectionAttribute buildElementCollectionAttribute = (BuildElementCollectionAttribute) Attribute.GetCustomAttribute(memInfo, typeof(BuildElementCollectionAttribute), false); if (buildElementCollectionAttribute != null) { XmlSchemaComplexType collectionType = new XmlSchemaComplexType(); XmlSchemaSequence sequence = new XmlSchemaSequence(); collectionType.Particle = sequence; sequence.MinOccurs = 0; sequence.MaxOccursString = "unbounded"; XmlSchemaElement itemType = new XmlSchemaElement(); itemType.Name = buildElementCollectionAttribute.ChildElementName; itemType.SchemaTypeName = FindOrCreateComplexType(childType).QualifiedName; sequence.Items.Add(itemType); childElement.SchemaType = collectionType; } else { childElement.SchemaTypeName = FindOrCreateComplexType(childType).QualifiedName; } // lazy init of sequence if (group1 == null) { group1 = CreateXsdSequence(0, Decimal.MaxValue); ct.Particle = group1; } group1.Items.Add(childElement); } } // allow attributes from other namespace ct.AnyAttribute = new XmlSchemaAnyAttribute(); ct.AnyAttribute.Namespace = "##other"; ct.AnyAttribute.ProcessContents = XmlSchemaContentProcessing.Skip; Schema.Items.Add(ct); Compile(); return ct; }
private static void ApplyAnnotation(XmlSchemaAnnotated annotatedType, DescriptionAttribute[] descriptionAtts, ConfigurationPropertyAttribute configProperty, string xmlDocumentation, string typeName, string fullName) { string standardDesc; if (configProperty != null) { standardDesc = configProperty.IsRequired ? "Required" : "Optional"; standardDesc += " " + fullName; standardDesc += " " + (configProperty.DefaultValue == null || configProperty.DefaultValue.ToString() == "System.Object" ? string.Empty : "[" + configProperty.DefaultValue + "]"); } else { standardDesc = string.Empty; } var documentation = new XmlSchemaDocumentation(); if (descriptionAtts.Length > 0) { documentation.Markup = TextToNodeArray(descriptionAtts[0].Description + " " + standardDesc); } else if (!String.IsNullOrEmpty(xmlDocumentation)) { // normalise line endings and remove trailing whitespace(s) xmlDocumentation = Regex.Replace(xmlDocumentation, @"\s*(\r\n|\n\r|\n|\r)", "\r\n"); documentation.Markup = TextToNodeArray(xmlDocumentation); } else { documentation.Markup = TextToNodeArray(standardDesc); } // machine documentation var appInfo = new XmlSchemaAppInfo { Markup = TextToNodeArray(typeName) }; // add the documentation to the object annotatedType.Annotation.Items.Add(documentation); annotatedType.Annotation.Items.Add(appInfo); }
///<summary>Generate XML schema for the given types ///</summary> ///<param name="ns">Default namespace</param> ///<param name="types">Types to include into schema</param> ///<param name="root">Root element</param> ///<param name="interfaces">Interface types</param> ///<returns>Built schema</returns> public static XmlSchema BuildSchema(string ns, Type[] types, Type root, Type[] interfaces) { XmlSchema xmlSchema = new XmlSchema(); xmlSchema.Namespaces.Add("xsd", "http://www.w3.org/2001/XMLSchema"); xmlSchema.Namespaces.Add("xsi", "http://www.w3.org/2001/XMLSchema-instance"); xmlSchema.ElementFormDefault = XmlSchemaForm.Qualified; xmlSchema.AttributeFormDefault = XmlSchemaForm.Unqualified; xmlSchema.Namespaces.Add("ns", ns); xmlSchema.TargetNamespace = ns; // Comment XmlSchemaAnnotation annotation = new XmlSchemaAnnotation(); XmlSchemaDocumentation documentation = new XmlSchemaDocumentation(); XmlDocument helperDocument = new XmlDocument(); string comment = String.Format(" XML schema for {0} , generated at {1} ", ns, DateTime.Now.ToString()); documentation.Markup = new XmlNode[1] { helperDocument.CreateComment(comment) }; annotation.Items.Add(documentation); xmlSchema.Items.Add(annotation); // Create group "action" to refer to any action var ints = new Dictionary<Type, XmlSchemaGroup>(); if (interfaces != null) { foreach (var intf in interfaces) { var action = new XmlSchemaGroup(); action.Name = getXmlTypeName(intf); action.Particle = new XmlSchemaChoice(); xmlSchema.Items.Add(action); ints.Add(intf, action); } } Dictionary<Type, XmlSchemaType> xmlTypes = new Dictionary<Type, XmlSchemaType>(); foreach (var type in types) { // If it does not have our XML header - skip it var na = (CustomAttributeHelper.First<XsTypeAttribute>(type)); if (na == null) continue; // Check if it is complex or simple XmlSchemaComplexType ct = new XmlSchemaComplexType(); ct.Name = getXmlTypeName(type); XmlSchemaObjectCollection attr = createComplexType(type, ct, ns, ints); // Add the new element as an option to the "action" group foreach (var i in ints) { bool isAction = (type.FindInterfaces((tp, nu) => tp == i.Key, null).Length != 0); if (isAction) { foreach (var tp in CustomAttributeHelper.All<XsTypeAttribute>(type)) { if (!string.IsNullOrEmpty(tp.Name)) i.Value.Particle.Items.Add(new XmlSchemaElement { Name = tp.Name, MinOccurs = 0, SchemaTypeName = new XmlQualifiedName(ct.Name, ns) }); } } } // Work with attributes foreach (var o in generateAttributes(xmlSchema, type, xmlTypes, ns)) attr.Add(o); if (na.AnyAttribute) { ct.AnyAttribute = new XmlSchemaAnyAttribute { ProcessContents = XmlSchemaContentProcessing.Skip }; } // Add type to the list xmlTypes.Add(type, ct); xmlSchema.Items.Add(ct); if (root.IsAssignableFrom(type)) { // Add all variations of Script names as element foreach (var o in CustomAttributeHelper.All<XsTypeAttribute>(root)) { xmlSchema.Items.Add(new XmlSchemaElement { Name = o.Name, SchemaTypeName = new XmlQualifiedName(xmlTypes[typeof(Script)].Name, ns) }); } } } return xmlSchema; }
/// <summary> /// Generate the interactions /// </summary> private void GenerateInteractions() { ClassRepository classRep = hostContext.Data["SourceCR"] as ClassRepository; // XSLT Generator XsltGenerator xsltGenerator = new XsltGenerator() { DataTypesXsd = dataTypes, OutputDir = Path.Combine(outputDir, "xslt"), TargetNamespace = targetNs }; RimXsltGenerator rimXsltGenerator = new RimXsltGenerator() { DataTypesXsd = dataTypes, OutputDir = Path.Combine(outputDir, "xslt") }; // Create the file Directory.CreateDirectory(xsltGenerator.OutputDir); // Interactions var interactions = from clsRep in classRep where clsRep.Value is Interaction select clsRep.Value as Interaction; // Generate XSD for interactions foreach (var iType in interactions) { System.Diagnostics.Trace.WriteLine(String.Format("Generating {0}.XSD...", iType.Name), "debug"); XmlSchema schema = new XmlSchema() { TargetNamespace = targetNs, Namespaces = new System.Xml.Serialization.XmlSerializerNamespaces( new XmlQualifiedName[] { new XmlQualifiedName("", targetNs) }) }; // Includes List<String> includedModels = new List<string>() { "InfrastructureRoot" }; // Generate the data types List<TypeReference> additionalComplexTypes = new List<TypeReference>(); List<XmlSchemaComplexType> complexTypes = GenerateComplexTypes(iType.MessageType, iType, includedModels, additionalComplexTypes); // Was there no complex types generated, if so we have to include the type model if (complexTypes.Count == 0) includedModels.Add(iType.MessageType.Class.ContainerName); // Generate the required additional types for (int i = 0; i < additionalComplexTypes.Count; i++) { TypeReference tr = additionalComplexTypes[i].Clone() as TypeReference; tr.Container = additionalComplexTypes[i].Container; // Resolve any cascaded generic parameters for (int s = 0; s < tr.GenericSupplier.Count; s++) tr.GenericSupplier[s] = ResolveGenericParameter(iType.MessageType, tr.GenericSupplier[s] as TypeParameter); // Fix the generic supplier for this type reference complexTypes.AddRange(GenerateComplexTypes(tr, iType, includedModels, additionalComplexTypes)); } // Process additional Includes foreach(string include in includedModels) schema.Includes.Add(new XmlSchemaInclude() { SchemaLocation = String.Format("./{0}",Path.ChangeExtension(include, "xsd")) }); string baseTypeName = complexTypes.Count == 0 ? iType.MessageType.Name : String.Format("{0}.{1}", iType.Name, iType.MessageType.Name); // Setup the anonymous class that extends the model XmlSchemaComplexContentExtension interactionContentExtension = new XmlSchemaComplexContentExtension() { BaseTypeName = new XmlQualifiedName(baseTypeName, targetNs) }; XmlSchemaComplexContent interactionContent = new XmlSchemaComplexContent() { Content = interactionContentExtension }; XmlSchemaComplexType interactionType = new XmlSchemaComplexType() { ContentModel = interactionContent }; interactionContentExtension.Attributes.Add(new XmlSchemaAttribute() { Use= XmlSchemaUse.Required, FixedValue = itsString, Name = "ITSVersion", SchemaTypeName = new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema") }); XmlSchemaElement element = new XmlSchemaElement() { Name = iType.Name, IsAbstract = false, SchemaType = interactionType }; // Add annotations if (!Documentation.IsEmpty(iType.Documentation)) { XmlSchemaDocumentation documentation = new XmlSchemaDocumentation(); XmlDocument documentationMarkup = new XmlDocument(); documentationMarkup.LoadXml("<div xmlns=\"http://www.w3.org/1999/xhtml\">" + iType.Documentation.ToString() + "</div>"); documentation.Markup = new List<XmlNode>(documentationMarkup.ChildNodes.Cast<XmlNode>()).ToArray(); element.Annotation = new XmlSchemaAnnotation(); element.Annotation.Items.Add(documentation); } schema.Items.Add(element); // ADd the types to the schema foreach (XmlSchemaComplexType t in complexTypes) { // Don't add duplicates var currentItems = from XmlSchemaObject obj in schema.Items where obj is XmlSchemaComplexType && (obj as XmlSchemaComplexType).Name == t.Name select obj; if (currentItems.Count() == 0 && t != null) schema.Items.Add(t); } // Write to the text writer TextWriter tw = null; try { tw = File.CreateText(Path.ChangeExtension(Path.Combine(outputDir, iType.Name), "xsd")); schema.Write(tw); } catch (Exception e) { System.Diagnostics.Debug.WriteLine(e.Message, "error"); } finally { if (tw != null) tw.Close(); } // Generate the XSLTs if (xslt) { xsltGenerator.GenerateCollapsingXslt(iType); xsltGenerator.GenerateExpandingXslt(iType); } if (xsltRim) { rimXsltGenerator.GenerateRIMGraph(iType); rimXsltGenerator.GenerateRIMParse(iType); } } }
private void SetContainer(State state, object container) { switch (state) { case State.Root: break; case State.Schema: break; case State.Annotation: this.annotation = (XmlSchemaAnnotation)container; break; case State.Include: this.include = (XmlSchemaInclude)container; break; case State.Import: this.import = (XmlSchemaImport)container; break; case State.Element: this.element = (XmlSchemaElement)container; break; case State.Attribute: this.attribute = (XmlSchemaAttribute)container; break; case State.AttributeGroup: this.attributeGroup = (XmlSchemaAttributeGroup)container; break; case State.AttributeGroupRef: this.attributeGroupRef = (XmlSchemaAttributeGroupRef)container; break; case State.AnyAttribute: this.anyAttribute = (XmlSchemaAnyAttribute)container; break; case State.Group: this.group = (XmlSchemaGroup)container; break; case State.GroupRef: this.groupRef = (XmlSchemaGroupRef)container; break; case State.All: this.all = (XmlSchemaAll)container; break; case State.Choice: this.choice = (XmlSchemaChoice)container; break; case State.Sequence: this.sequence = (XmlSchemaSequence)container; break; case State.Any: this.anyElement = (XmlSchemaAny)container; break; case State.Notation: this.notation = (XmlSchemaNotation)container; break; case State.SimpleType: this.simpleType = (XmlSchemaSimpleType)container; break; case State.ComplexType: this.complexType = (XmlSchemaComplexType)container; break; case State.ComplexContent: this.complexContent = (XmlSchemaComplexContent)container; break; case State.ComplexContentExtension: this.complexContentExtension = (XmlSchemaComplexContentExtension)container; break; case State.ComplexContentRestriction: this.complexContentRestriction = (XmlSchemaComplexContentRestriction)container; break; case State.SimpleContent: this.simpleContent = (XmlSchemaSimpleContent)container; break; case State.SimpleContentExtension: this.simpleContentExtension = (XmlSchemaSimpleContentExtension)container; break; case State.SimpleContentRestriction: this.simpleContentRestriction = (XmlSchemaSimpleContentRestriction)container; break; case State.SimpleTypeUnion: this.simpleTypeUnion = (XmlSchemaSimpleTypeUnion)container; break; case State.SimpleTypeList: this.simpleTypeList = (XmlSchemaSimpleTypeList)container; break; case State.SimpleTypeRestriction: this.simpleTypeRestriction = (XmlSchemaSimpleTypeRestriction)container; break; case State.Unique: case State.Key: case State.KeyRef: this.identityConstraint = (XmlSchemaIdentityConstraint)container; break; case State.Selector: case State.Field: this.xpath = (XmlSchemaXPath)container; break; case State.MinExclusive: case State.MinInclusive: case State.MaxExclusive: case State.MaxInclusive: case State.TotalDigits: case State.FractionDigits: case State.Length: case State.MinLength: case State.MaxLength: case State.Enumeration: case State.Pattern: case State.WhiteSpace: this.facet = (XmlSchemaFacet)container; break; case State.AppInfo: this.appInfo = (XmlSchemaAppInfo)container; break; case State.Documentation: this.documentation = (XmlSchemaDocumentation)container; break; case State.Redefine: this.redefine = (XmlSchemaRedefine)container; break; default: Debug.Assert(false, "State is " + state); break; } }
private void Write6_XmlSchemaDocumentation(XmlSchemaDocumentation o) { if (o != null) { this.WriteStartElement("documentation"); this.WriteAttribute("source", "", o.Source); this.WriteAttribute("lang", "http://www.w3.org/XML/1998/namespace", o.Language); XmlNode[] markup = o.Markup; if (markup != null) { for (int i = 0; i < markup.Length; i++) { XmlNode node = markup[i]; this.WriteStartElement("node"); this.WriteAttribute("xml", "", node.OuterXml); } } this.WriteEndElement(); } }
//<documentation // source = anyURI // xml:lang = language> // Content: ({any})* //</documentation> internal static XmlSchemaDocumentation Read(XmlSchemaReader reader, ValidationEventHandler h, out bool skip) { skip = false; XmlSchemaDocumentation doc = new XmlSchemaDocumentation(); reader.MoveToElement(); if (reader.NamespaceURI != XmlSchema.Namespace || reader.LocalName != "documentation") { error(h, "Should not happen :1: XmlSchemaDocumentation.Read, name=" + reader.Name, null); reader.Skip(); return(null); } doc.LineNumber = reader.LineNumber; doc.LinePosition = reader.LinePosition; doc.SourceUri = reader.BaseURI; while (reader.MoveToNextAttribute()) { if (reader.Name == "source") { doc.source = reader.Value; } else if (reader.Name == "xml:lang") { doc.language = reader.Value; } else { error(h, reader.Name + " is not a valid attribute for documentation", null); } } reader.MoveToElement(); if (reader.IsEmptyElement) { doc.Markup = new XmlNode[0]; return(doc); } //Content {any}* XmlDocument xmldoc = new XmlDocument(); xmldoc.AppendChild(xmldoc.ReadNode(reader)); XmlNode root = xmldoc.FirstChild; if (root != null && root.ChildNodes != null) { doc.Markup = new XmlNode[root.ChildNodes.Count]; for (int i = 0; i < root.ChildNodes.Count; i++) { doc.Markup[i] = root.ChildNodes[i]; } } if (reader.NodeType == XmlNodeType.Element || reader.NodeType == XmlNodeType.EndElement) { skip = true; } return(doc); }
/// <summary> /// Create CodeCommentStatement from schema documentation. /// </summary> /// <param name="codeStatmentColl">CodeCommentStatementCollection collection</param> /// <param name="xmlDoc">Schema documentation</param> protected virtual void CreateCommentStatment( CodeCommentStatementCollection codeStatmentColl, XmlSchemaDocumentation xmlDoc) { codeStatmentColl.Clear(); foreach (XmlNode itemDoc in xmlDoc.Markup) { var textLine = itemDoc.InnerText.Trim(); if (textLine.Length > 0) CodeDomHelper.CreateSummaryComment(codeStatmentColl, textLine); } }