void AddElementToSchema(XmlSchemaElement element, string elementNs, XmlSchemaSet schemaSet) { OperationDescription parentOperation = this.operation; if (parentOperation.OperationMethod != null) { XmlQualifiedName qname = new XmlQualifiedName(element.Name, elementNs); OperationElement existingElement; if (ExportedMessages.ElementTypes.TryGetValue(qname, out existingElement)) { if (existingElement.Operation.OperationMethod == parentOperation.OperationMethod) return; if (!SchemaHelper.IsMatch(element, existingElement.Element)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.CannotHaveTwoOperationsWithTheSameElement5, parentOperation.OperationMethod.DeclaringType, parentOperation.OperationMethod.Name, qname, existingElement.Operation.OperationMethod.DeclaringType, existingElement.Operation.Name))); } return; } else { ExportedMessages.ElementTypes.Add(qname, new OperationElement(element, parentOperation)); } } SchemaHelper.AddElementToSchema(element, SchemaHelper.GetSchema(elementNs, schemaSet), schemaSet); }
public static void ReplaceThisWith(this XmlSchemaElement that, XmlSchemaElement with) { var gr = that.Parent as XmlSchemaGroupBase; int idx = gr.Items.IndexOf(that); gr.Items.Insert(idx, with); gr.Items.Remove(that); }
public void Bug360541 () { XmlSchemaComplexType stype = GetStype (); XmlSchemaElement selem1 = new XmlSchemaElement (); selem1.Name = "schema"; selem1.SchemaType = stype; XmlSchema schema = new XmlSchema (); schema.Items.Add (selem1); XmlSchemas xs = new XmlSchemas (); xs.Add (schema); xs.Find (XmlQualifiedName.Empty, typeof (XmlSchemaElement)); selem1 = new XmlSchemaElement (); selem1.Name = "schema1"; selem1.SchemaType = stype; schema = new XmlSchema (); schema.Items.Add (selem1); xs = new XmlSchemas (); xs.Add (schema); xs.Find (XmlQualifiedName.Empty, typeof (XmlSchemaElement)); }
public void TestAdd () { XmlSchemaCollection col = new XmlSchemaCollection (); XmlSchema schema = new XmlSchema (); XmlSchemaElement elem = new XmlSchemaElement (); elem.Name = "foo"; schema.Items.Add (elem); schema.TargetNamespace = "urn:foo"; col.Add (schema); col.Add (schema); // No problem !? XmlSchema schema2 = new XmlSchema (); schema2.Items.Add (elem); schema2.TargetNamespace = "urn:foo"; col.Add (schema2); // No problem !! schema.Compile (null); col.Add (schema); col.Add (schema); // Still no problem !!! schema2.Compile (null); col.Add (schema2); schema = GetSchema ("Test/XmlFiles/xsd/3.xsd"); schema.Compile (null); col.Add (schema); schema2 = GetSchema ("Test/XmlFiles/xsd/3.xsd"); schema2.Compile (null); col.Add (schema2); }
public DescriptrosCollector(XmlSchemaElement element) { if (element == null) throw new ArgumentNullException("element"); this.element = element; Collect(); }
internal SchemaObjectInfo(XmlSchemaType type, XmlSchemaElement element, XmlSchema schema, List<XmlSchemaType> knownTypes) { this.type = type; this.element = element; this.schema = schema; this.knownTypes = knownTypes; }
/// <summary> /// Gets the XML schema. /// </summary> /// <param name="type">The type.</param> /// <param name="schemaSet">The schema set.</param> /// <param name="generateFlatSchema">A value indicating whether the schema should be generated as flat schema.</param> /// <returns>The qualified name of the type.</returns> /// <exception cref="ArgumentNullException">The <paramref name="schemaSet"/> is <c>null</c>.</exception> public static XmlQualifiedName GetXmlSchema(Type type, XmlSchemaSet schemaSet, bool generateFlatSchema) { Argument.IsNotNull("schemaSet", schemaSet); var dependencyResolver = IoCConfiguration.DefaultDependencyResolver; var serializationManager = dependencyResolver.Resolve<ISerializationManager>(); string typeNs = GetTypeNamespaceForSchema(type); var schema = GetOrCreateSchema(typeNs, schemaSet, serializationManager); // Check if it already exists string typeName = GetTypeNameForSchema(type); var existingType = (from x in schema.Items.Cast<object>() where x is XmlSchemaComplexType && ((XmlSchemaComplexType)x).Name == typeName select (XmlSchemaComplexType)x).FirstOrDefault(); if (existingType != null) { return new XmlQualifiedName(existingType.Name, typeNs); } var typeSchema = CreateSchemaComplexType(type, schema, schemaSet, serializationManager, generateFlatSchema); var root = new XmlSchemaElement(); root.Name = string.Format("{0}", typeSchema.Name); root.SchemaTypeName = new XmlQualifiedName(typeSchema.Name, typeNs); root.IsNillable = true; schema.Items.Add(root); return new XmlQualifiedName(typeSchema.Name, typeNs); }
internal string GenerateTypedDataSet(XmlSchemaElement element, XmlSchemas schemas, CodeCompileUnit compileUnit, CodeNamespace mainNamespace, CodeDomProvider codeProvider) { if (element == null) { return null; } if (this.importedTypes[element.SchemaType] != null) { return (string) this.importedTypes[element.SchemaType]; } IList list = schemas.GetSchemas(element.QualifiedName.Namespace); if (list.Count != 1) { return null; } XmlSchema schema = list[0] as XmlSchema; if (schema == null) { return null; } MemoryStream stream = new MemoryStream(); schema.Write(stream); stream.Position = 0L; DesignDataSource designDS = new DesignDataSource(); designDS.ReadXmlSchema(stream, null); stream.Close(); string str = TypedDataSetGenerator.GenerateInternal(designDS, compileUnit, mainNamespace, codeProvider, this.dataSetGenerateOptions, null); this.importedTypes.Add(element.SchemaType, str); return str; }
private void ProcessLax(Choice c, string ns) { foreach (Particle p in c.Items) { Element el = p as Element; if (el == null) { throw Error(c, String.Format("Target schema item contains unacceptable particle {0}. Only element is allowed here.")); } if (ElementMatches(el, ns)) { InferElement(el, ns, false); return; } } // append a new element particle to lax term. Element nel = new Element(); if (source.NamespaceURI == ns) { nel.Name = source.LocalName; } else { nel.RefName = new QName(source.LocalName, source.NamespaceURI); AddImport(ns, source.NamespaceURI); } InferElement(nel, source.NamespaceURI, true); c.Items.Add(nel); }
internal static void AddElementForm(XmlSchemaElement element, System.Xml.Schema.XmlSchema schema) { if (schema.ElementFormDefault != XmlSchemaForm.Qualified) { element.Form = XmlSchemaForm.Qualified; } }
public void TestSimpleValidation () { string xml = "<root/>"; xvr = PrepareXmlReader (xml); Assert.AreEqual (ValidationType.Auto, xvr.ValidationType); XmlSchema schema = new XmlSchema (); XmlSchemaElement elem = new XmlSchemaElement (); elem.Name = "root"; schema.Items.Add (elem); xvr.Schemas.Add (schema); xvr.Read (); // root Assert.AreEqual (ValidationType.Auto, xvr.ValidationType); xvr.Read (); // EOF xml = "<hoge/>"; xvr = PrepareXmlReader (xml); xvr.Schemas.Add (schema); try { xvr.Read (); Assert.Fail ("element mismatch is incorrectly allowed"); } catch (XmlSchemaException) { } xml = "<hoge xmlns='urn:foo' />"; xvr = PrepareXmlReader (xml); xvr.Schemas.Add (schema); try { xvr.Read (); Assert.Fail ("Element in different namespace is incorrectly allowed."); } catch (XmlSchemaException) { } }
private void Run() { // XmlSchemaSet need to be compiled. schemas.Compile(); // move to top-level element source.MoveToContent(); int depth = source.Depth; if (source.NodeType != XmlNodeType.Element) { throw new ArgumentException("Argument XmlReader content is expected to be an element."); } QName qname = new QName(source.LocalName, source.NamespaceURI); Element el = GetGlobalElement(qname); if (el == null) { el = CreateGlobalElement(qname); InferElement(el, qname.Namespace, true); } else { InferElement(el, qname.Namespace, false); } // FIXME: compile again. // foreach (XmlSchema schema in schemas.Schemas ()) // schemas.Reprocess (schema); }
private void BuildProperties(XmlSchemaElement parentElement, XmlSchemaType schemaType, ClrContentTypeInfo typeInfo) { XmlSchemaComplexType ct = schemaType as XmlSchemaComplexType; if (ct != null) { if (ct.TypeCode == XmlTypeCode.Item) { return; } XmlSchemaParticle particleToProperties = ct.ContentTypeParticle; XmlSchemaComplexType baseType = ct.BaseXmlSchemaType as XmlSchemaComplexType; if (schemaType.GetContentType() == XmlSchemaContentType.TextOnly) { //Try to create a text property for the simple content ClrPropertyInfo property = BuildComplexTypeTextProperty(parentElement, ct); if (property != null) { typeInfo.AddMember(property); } if (baseType == null) { //Derived from Simple type, first step simpleContent extension TraverseAttributes(ct.AttributeUses, typeInfo); } else { //Derived from another complex type simple content, generate the content only if there are additional restrictions if (!ct.IsDerivedByRestriction()) //process attributes only if not derived by restriction { TraverseAttributes(ct.AttributeUses, baseType.AttributeUses, typeInfo); } } } else { Debug.Assert( baseType != null); //ComplexType with complexContent is always derived from another complexType if (ct.IsDerivedByRestriction()) { //Do not handle restrictions on complex content? return; } if (particleToProperties.GetParticleType() != ParticleType.Empty) { TraverseParticle(particleToProperties, baseType, typeInfo, ct.DerivedBy); } TraverseAttributes(ct.AttributeUses, baseType.AttributeUses, typeInfo); } } else { typeInfo.AddMember(BuildSimpleTypeTextProperty(parentElement, schemaType as XmlSchemaSimpleType)); } }
internal void CheckDuplicateElement(XmlSchemaElement element, string elementNs) { if ((element != null) && ((element.Parent != null) && (element.Parent is XmlSchema))) { XmlSchemaObjectTable elements = null; if ((this.Schema != null) && (this.Schema.TargetNamespace == elementNs)) { XmlSchemas.Preprocess(this.Schema); elements = this.Schema.Elements; } else if (this.Schemas != null) { elements = this.Schemas.GlobalElements; } else { return; } foreach (XmlSchemaElement element2 in elements.Values) { if ((element2.Name == element.Name) && (element2.QualifiedName.Namespace == elementNs)) { if (!this.Match(element2, element)) { throw new InvalidOperationException(Res.GetString("XmlSerializableRootDupName", new object[] { this.getSchemaMethod.DeclaringType.FullName, element2.Name, elementNs })); } break; } } } }
protected override void Visit(XmlSchemaElement element) { var sameNamespace = element.QualifiedName.Namespace == _targetNamespace || string.IsNullOrEmpty(element.QualifiedName.Namespace) && string.IsNullOrEmpty(_targetNamespace); if (!sameNamespace) return; var isGlobal = (element.Parent is XmlSchema); if (isGlobal) { _elements.Add(element); base.Visit(element); } else if (element.RefName.IsEmpty) { base.Visit(element); } else { var elementParent = FindOuterMostElement(element); var referencedElement = (XmlSchemaElement)_schemaSet.GlobalElements[element.RefName]; if (referencedElement != elementParent) _referencedElements.Add(referencedElement); } }
internal string GenerateTypedDataSet(XmlSchemaElement element, XmlSchemas schemas, CodeNamespace codeNamespace, StringCollection references, CodeDomProvider codeProvider) { if (element == null) { return null; } if (this.importedTypes[element.SchemaType] != null) { return (string) this.importedTypes[element.SchemaType]; } IList list = schemas.GetSchemas(element.QualifiedName.Namespace); if (list.Count != 1) { return null; } XmlSchema schema = list[0] as XmlSchema; if (schema == null) { return null; } DataSet dataSet = new DataSet(); using (MemoryStream stream = new MemoryStream()) { schema.Write(stream); stream.Position = 0L; dataSet.ReadXmlSchema(stream); } string name = new TypedDataSetGenerator().GenerateCode(dataSet, codeNamespace, codeProvider.CreateGenerator()).Name; this.importedTypes.Add(element.SchemaType, name); references.Add("System.Data.dll"); return name; }
public DocUIList(XmlNode xmlNode, XmlSchemaAnnotated xsdNode, Panel contentpanel, Panel overlaypanel, DynamicForm parentForm, bool horizontal = true) : base(xmlNode, xsdNode, contentpanel, overlaypanel, parentForm) { _optlist = new List<ListItemComponent>(); _parent = xmlNode; _listpanel = new StackPanel(); _listpanel.Orientation = horizontal ? Orientation.Horizontal : Orientation.Vertical; XmlSchemaElement schemaEl = xsdNode as XmlSchemaElement; if (schemaEl != null) { XmlSchemaSequence seq = XmlSchemaUtilities.tryGetSequence(schemaEl.ElementSchemaType); if (seq != null && seq.Items.Count == 1 && seq.Items[0] is XmlSchemaElement) { _el = seq.Items[0] as XmlSchemaElement; //get all elements from current node foreach (XmlNode node in xmlNode.ChildNodes) { ListItemComponent lio = new ListItemComponent(node, _el, _listpanel, overlaypanel, _optlist, parentForm); _optlist.Add(lio); } } Button add = new Button(); add.Content = "Add item"; add.Click += AddItem; _listpanel.Children.Add(add); contentpanel.Children.Add(_listpanel); } }
/*public string GenerateXmlString(XmlSchemaParticle root) * { * string tag = null; * if (root is XmlSchemaElement) * { * XmlSchemaElement elem = root as XmlSchemaElement; * tag += '<' + elem.Name + '>'; * if (elem.RefName.IsEmpty) * { //sequence * XmlSchemaType type = (XmlSchemaType)elem.ElementSchemaType; * //XmlSchemaComplexType complexType = type as XmlSchemaComplexType; * if (type is XmlSchemaComplexType) * { * XmlSchemaComplexType complexType = type as XmlSchemaComplexType; * if (complexType.QualifiedName.IsEmpty) * //if (!((elem.Parent is XmlSchemaComplexType) || (elem.Parent is XmlSchemaSimpleType))) * { * tag += '<' + elem.Name + '>'; * tag += GenerateXmlString(complexType.ContentTypeParticle); * tag += "</" + elem.Name + ">"; * }*/ /*else * { * }*//* * } * } * tag += "</"+elem.Name+">"; * *//*else * { //is it simpletype * XmlSchemaSimpleType simpleType = ((XmlSchemaType)elem.ElementSchemaType) as XmlSchemaSimpleType; * //SimpleType element restriction, maxinclusive, mininclusive, * if (simpleType != null) * { //Need to take care of restriction, list or union types here * //simpleType.TypeCode * if (simpleType.Name == null) * { * } * else * { * } * } * }*//* * * //} * * } * else * if (root is XmlSchemaGroupBase) * { //It xs:all, * XmlSchemaGroupBase baseParticle = root as XmlSchemaGroupBase; * //tag += baseParticle.Name * foreach (XmlSchemaParticle subParticle in baseParticle.Items) * { * tag += GenerateXmlString(subParticle); * } * } * return tag; * }*/ public XmlSchemaObject SearchNode(XmlSchema xs, string name) { XmlSchemaObject returnval = null; foreach (object item in xs.Items) { System.Xml.Schema.XmlSchemaElement xse = item as System.Xml.Schema.XmlSchemaElement; System.Xml.Schema.XmlSchemaComplexType xsct = item as System.Xml.Schema.XmlSchemaComplexType; if (xse != null) { if (xse.Name == name) { returnval = xse; } } else { if (xsct != null) { if (xsct.Name == name) { returnval = xsct; } } } } return(returnval); }
private sch.XmlSchemaAll GenOneTabElement(sch.XmlSchemaAll curElement, string tableAlias, List <string> tabCols, List <string> tabColTypes) { sch.XmlSchemaElement rootElement = new sch.XmlSchemaElement(); rootElement.Name = tableAlias; rootElement.MinOccurs = 0; rootElement.MaxOccursString = "unbounded"; curElement.Items.Add(rootElement); sch.XmlSchemaComplexType rootType = new sch.XmlSchemaComplexType(); rootType.IsMixed = false; sch.XmlSchemaAll rootAll = new sch.XmlSchemaAll(); rootType.Particle = rootAll; rootElement.SchemaType = rootType; for (int i = 0; i < tabCols.Count; i++) { string colName = tabCols[i]; string type = tabColTypes[i]; sch.XmlSchemaElement column = new sch.XmlSchemaElement(); column.Name = colName; column.SchemaTypeName = new XmlQualifiedName(type, ns); rootAll.Items.Add(column); } return(rootAll); }
//gen new xsd base on selected tables and columns which generated by OSQL. private string CreateXsd() { xmlschema = new sch.XmlSchema(); //Create the PdeData element sch.XmlSchemaElement rootElement = new sch.XmlSchemaElement(); rootElement.Name = "PdeData"; xmlschema.Items.Add(rootElement); sch.XmlSchemaComplexType rootType = new sch.XmlSchemaComplexType(); rootType.IsMixed = false; sch.XmlSchemaAll rootAll = new sch.XmlSchemaAll(); rootType.Particle = rootAll; rootElement.SchemaType = rootType; for (int i = 0; i < selectedTables.Count; i++) { rootAll = GenOneTabElement(rootAll, selectedTables[i], selectedColumns[i], tabColsType[i]); } xmlschema.Compile(new sch.ValidationEventHandler(ValidationEventHandler)); FileStream stream = new FileStream("e:\\temp.xsd", FileMode.Create); //Write the file xmlschema.Write(stream); stream.Close(); return("e:\\temp.xsd"); }
private Element CreateElement(QName name) { Element el = new Element(); el.Name = name.Name; return(el); }
private void InferContent(Element el, string ns, bool isNew) { source.Read(); source.MoveToContent(); switch (source.NodeType) { case XmlNodeType.EndElement: InferAsEmptyElement(el, ns, isNew); break; case XmlNodeType.Element: InferComplexContent(el, ns, isNew); break; case XmlNodeType.Text: case XmlNodeType.CDATA: case XmlNodeType.SignificantWhitespace: InferTextContent(el, isNew); source.MoveToContent(); if (source.NodeType == XmlNodeType.Element) { goto case XmlNodeType.Element; } break; case XmlNodeType.Whitespace: InferContent(el, ns, isNew); // skip and retry break; } }
private void CreateSchema(String name, DataTable dt) { XmlSchema schema = new XmlSchema(); rootElem = new XmlSchemaElement(); rootElem.Name = XmlConvert.EncodeName(name); schema.Items.Add(rootElem); XmlSchemaComplexType rootContent = new XmlSchemaComplexType(); rootElem.SchemaType = rootContent; XmlSchemaSequence s1 = new XmlSchemaSequence(); rootContent.Particle = s1; rowElem = new XmlSchemaElement(); rowElem.Name = "row"; rowElem.MinOccurs = 0; rowElem.MaxOccursString = "unbounded"; s1.Items.Add(rowElem); XmlSchemaComplexType rowContent = new XmlSchemaComplexType(); rowElem.SchemaType = rowContent; XmlSchemaSequence s2 = new XmlSchemaSequence(); rowContent.Particle = s2; DataRow[] dt_rows = dt.Select(); dataElem = new XmlSchemaElement[dt_rows.Length]; dataContent = new XmlSchemaSimpleType[dt_rows.Length]; for (int k = 0; k < dt_rows.Length; k++) { DataRow r = dt_rows[k]; dataElem[k] = new XmlSchemaElement(); dataElem[k].Name = XmlConvert.EncodeName((String)r["ColumnName"]); if (r["AllowDBNull"] != DBNull.Value && (bool)r["AllowDBNull"]) dataElem[k].MinOccurs = 0; Type dataType = (Type)r["DataType"]; XmlTypeCode typeCode = XQuerySequenceType.GetXmlTypeCode(dataType); if (typeCode == XmlTypeCode.Item) dataContent[k] = null; else { dataContent[k] = XmlSchemaType.GetBuiltInSimpleType(typeCode); dataElem[k].SchemaTypeName = dataContent[k].QualifiedName; } s2.Items.Add(dataElem[k]); } m_schemaSet = new XmlSchemaSet(); m_schemaSet.Add(schema); m_schemaSet.Compile(); NewNode(XmlNodeType.XmlDeclaration, null, null, null); NewNode(XmlNodeType.Element, name, null, null); m_readState = ReadState.Initial; //XmlWriter writer = XmlWriter.Create("c:\\work\\schema.xml"); //schema.Write(writer); //writer.Close(); }
private ArrayList IsSubstitutionGroupHead(XmlSchemaElement element) { XmlQualifiedName elementName = element.QualifiedName; ArrayList memberList; substitutionGroups.TryGetValue(elementName, out memberList); return(memberList); }
/// <summary> /// Checks whether the element belongs to the XSD namespace. /// </summary> static bool IsXmlSchemaNamespaceElement(XmlSchemaElement element) { XmlQualifiedName qualifiedName = element.QualifiedName; if (qualifiedName != null) { return IsXmlSchemaNamespace(qualifiedName.Namespace); } return false; }
public override void FixtureInit() { XmlSchemaCompletionDataCollection schemas = new XmlSchemaCompletionDataCollection(); schemas.Add(SchemaCompletionData); XmlCompletionDataProvider provider = new XmlCompletionDataProvider(schemas, SchemaCompletionData, String.Empty); string xml = "<note xmlns='http://www.w3schools.com'></note>"; schemaElement = (XmlSchemaElement)XmlView.GetSchemaObjectSelected(xml, xml.IndexOf("note xmlns"), provider); }
public XElement CreateProtoElement(XmlSchemaElement schemaElement) { if (schemaElement.ElementSchemaType != null) { var nodes = CreateProtoAnyType(schemaElement.ElementSchemaType); return new XElement(schemaElement.QualifiedName.ToXName(), nodes); } else { throw new Exception("invalid schema type"); } }
protected override void Visit(XmlSchemaElement element) { if (!element.RefName.IsEmpty) return; PushNamedObject(element); base.Visit(element); PopNamedObject(); }
public virtual void VisitXmlSchemaElement(XmlSchemaElement element) { if (element.Name != null) VisitXmlSchemaElementNamed(element); else { VisitXmlSchemaElementNested(element); } }
private string genExpXsd() { sch.XmlSchema expSchema = new sch.XmlSchema(); //Create the PdeData element sch.XmlSchemaElement rootElement = new sch.XmlSchemaElement(); rootElement.Name = ROOT_ELEMENT; expSchema.Items.Add(rootElement); sch.XmlSchemaComplexType rootType = new sch.XmlSchemaComplexType(); rootType.IsMixed = false; sch.XmlSchemaSequence rootSequence = new sch.XmlSchemaSequence(); rootType.Particle = rootSequence; rootElement.SchemaType = rootType; foreach (ExportItemMap itemMap in exportItems) { if (itemMap.mapType == ProntoDoc.Framework.CoreObject.MapType.singleCell) { sch.XmlSchemaElement item = new sch.XmlSchemaElement(); item.Name = itemMap.treeNodeName; item.SchemaTypeName = new XmlQualifiedName(itemMap.dataType, ns); rootSequence.Items.Add(item); } else { sch.XmlSchemaElement tabElement = new sch.XmlSchemaElement(); tabElement.MinOccurs = 0; tabElement.MaxOccursString = "unbounded"; tabElement.Name = itemMap.treeNodeName; rootSequence.Items.Add(tabElement); sch.XmlSchemaComplexType tabType = new sch.XmlSchemaComplexType(); tabType.IsMixed = false; sch.XmlSchemaAll tabAll = new sch.XmlSchemaAll(); tabType.Particle = tabAll; tabElement.SchemaType = tabType; //generate children node foreach (TableColumnMap col in itemMap.tabCols) { sch.XmlSchemaElement item = new sch.XmlSchemaElement(); item.Name = col.treeNodeName; item.SchemaTypeName = new XmlQualifiedName(col.dataType, ns); tabAll.Items.Add(item); } } } expSchema.Compile(new sch.ValidationEventHandler(ValidationEventHandler)); FileStream stream = new FileStream("e:\\tempout.xsd", FileMode.Create); //Write the file expSchema.Write(stream); stream.Close(); return("e:\\tempout.xsd"); }
private Element CreateGlobalElement(QName name) { Element el = CreateElement(name); XmlSchema schema = PopulateSchema(name.Namespace); schema.Items.Add(el); newElements.Add(name, el); return(el); }
/// <summary> /// Формируем XmlSchema для правильного отображения индикаторов группы в VGridControl /// </summary> /// <param name="elmList">названия всех по</param> /// <returns>Возвращаем поток в который записана XmlSchema</returns> public static MemoryStream CreateXmlSchemaForIndicatorsInGroup(List<string[]> elmList) { var xmlSchema = new XmlSchema(); // <xs:element name="root"> var elementRoot = new XmlSchemaElement(); xmlSchema.Items.Add(elementRoot); elementRoot.Name = "root"; // <xs:complexType> var complexType = new XmlSchemaComplexType(); elementRoot.SchemaType = complexType; // <xs:choice minOccurs="0" maxOccurs="unbounded"> var choice = new XmlSchemaChoice(); complexType.Particle = choice; choice.MinOccurs = 0; choice.MaxOccursString = "unbounded"; // <xs:element name="record"> var elementRecord = new XmlSchemaElement(); choice.Items.Add(elementRecord); elementRecord.Name = "record"; // <xs:complexType> var complexType2 = new XmlSchemaComplexType(); elementRecord.SchemaType = complexType2; // <xs:sequence> var sequence = new XmlSchemaSequence(); complexType2.Particle = sequence; foreach (var el in elmList) { var element = new XmlSchemaElement(); sequence.Items.Add(element); element.Name = el[0]; element.SchemaTypeName = new XmlQualifiedName(el[1], "http://www.w3.org/2001/XMLSchema"); } var schemaSet = new XmlSchemaSet(); schemaSet.Add(xmlSchema); schemaSet.Compile(); XmlSchema compiledSchema = null; foreach (XmlSchema schema1 in schemaSet.Schemas()) compiledSchema = schema1; var nsmgr = new XmlNamespaceManager(new NameTable()); nsmgr.AddNamespace("xs", "http://www.w3.org/2001/XMLSchema"); var ms = new MemoryStream(); if (compiledSchema != null) compiledSchema.Write(ms, nsmgr); ms.Position = 0; return ms; }
private Element GetGlobalElement(QName name) { Element el = newElements [name] as Element; if (el == null) { el = schemas.GlobalElements [name] as Element; } return(el); }
//------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------ internal Element(XbrlSchema Schema, XmlSchemaElement SchemaElement) { this.Schema = Schema; thisSchemaElement = SchemaElement; this.Id = SchemaElement.Id; this.Name = SchemaElement.Name; this.TypeName = SchemaElement.SchemaTypeName; SetSubstitutionGroup(SchemaElement.SubstitutionGroup); SetPeriodType(); }
/// <summary> /// Insert an element above an existing any item. /// </summary> /// <param name="particle">The particle in which the any item should be found.</param> /// <param name="element">The element to insert.</param> /// <returns>true if the element was inserted; false otherwise.</returns> private bool InsertElement(XmlSchemaParticle particle, XmlSchemaElement element) { if (particle is XmlSchemaChoice) { XmlSchemaChoice choice = (XmlSchemaChoice)particle; for (int i = 0; i < choice.Items.Count; i++) { XmlSchemaParticle childParticle = (XmlSchemaParticle)choice.Items[i]; if (childParticle is XmlSchemaAny) { // index this any element for later removal this.anys[childParticle] = choice; choice.Items.Insert(i, element); return true; } else { if (this.InsertElement(childParticle, element)) { return true; } } } } else if (particle is XmlSchemaSequence) { XmlSchemaSequence sequence = (XmlSchemaSequence)particle; for (int i = 0; i < sequence.Items.Count; i++) { XmlSchemaParticle childParticle = (XmlSchemaParticle)sequence.Items[i]; if (childParticle is XmlSchemaAny) { // index this any element for later removal this.anys[childParticle] = sequence; sequence.Items.Insert(i, element); return true; } else { if (this.InsertElement(childParticle, element)) { return true; } } } } return false; }
public static void AssertElement (XmlSchemaElement element, string name, XmlQualifiedName refName, string id, XmlQualifiedName schemaTypeName, XmlSchemaType schemaType) { Assert.IsNotNull (element); Assert.AreEqual (name, element.Name); Assert.AreEqual (refName, element.RefName); Assert.AreEqual (id, element.Id); Assert.AreEqual (schemaTypeName, element.SchemaTypeName); Assert.AreEqual (schemaType, element.SchemaType); }
private static decimal FixMaxOccurs(XmlSchemaElement schemaElement, string parentName) { if (schemaElement.Name == "name" && parentName == "application") { return 3; } else { return schemaElement.MaxOccurs; } }
public static XmlSchemaElement FindAlternative(XmlSchemaElement el, string elementName) { foreach (XmlSchemaElement found in GetAlternatives(el)) { if (GetName(found) == elementName) { return found; } } return null; }
private ProjectionElement CreateElement(XmlSchemaElement element) { ProjectionElement newElement; var nmspc = element.QualifiedName.Namespace; var name = element.QualifiedName.Name; var schemeType = GetResourceElementType(element); Type currentResourceType = null; if (schemeType!=null) { newElement = new ResourceProjectionElement { Name = name, Namespace = nmspc, ResourceType = schemeType, SchemeType = schemeType }; currentResourceType = _innerCachier.GetTypeByName(schemeType); } else { newElement = new ProjectionElement { Name = name, Namespace = nmspc }; } if (_projectionResources.ContainsKey(nmspc) && _projectionResources[nmspc].ContainsKey(name)) newElement.PropertyFiller = _projectionResources[nmspc][name]; newElement.FillingInfo = new FillingInfo(); foreach(var property in (element.ElementSchemaType as XmlSchemaComplexType) .AttributeUses .Values .OfType<XmlSchemaAttribute>() .Where(k=>k.QualifiedName.Namespace != QueryStorage.QuerySpace) .Select(k => k.QualifiedName.Name)) { if (currentResourceType != null && (currentResourceType.GetProperty(property) != null || currentResourceType.GetField(property) != null)) newElement.FillingInfo.Add(property,FillingInfo.FillType.Native); else { newElement.FillingInfo.Add(property, FillingInfo.FillType.ByFiller); } } if (element.ElementSchemaType.Name != null) { Debug.Assert(FindElement(element) == null); _globalElements.Add(newElement); } return newElement; }
internal void Clear() { this.isNil = false; this.isDefault = false; this.schemaType = null; this.schemaElement = null; this.schemaAttribute = null; this.memberType = null; this.validity = XmlSchemaValidity.NotKnown; this.contentType = XmlSchemaContentType.Empty; }
protected void AssertElement (XmlSchemaElement element, string name, XmlQualifiedName refName, string id, XmlQualifiedName schemaTypeName, XmlSchemaType schemaType) { AssertNotNull (element); AssertEquals (name, element.Name); AssertEquals (refName, element.RefName); AssertEquals (id, element.Id); AssertEquals (schemaTypeName, element.SchemaTypeName); AssertEquals (schemaType, element.SchemaType); }
public static void AddElementToSchema(XmlSchema xmlSchema, string elementName, string elementType, string xmlNamespace) { XmlSchemaElement testNode = new XmlSchemaElement(); testNode.Name = elementName; testNode.Namespaces.Add("", xmlNamespace); testNode.SchemaTypeName = new XmlQualifiedName(elementType, xmlNamespace); xmlSchema.Items.Add(testNode); XmlSchemaSet schemaSet = new XmlSchemaSet(); schemaSet.Add(xmlSchema); schemaSet.Compile(); }
private Schema.XmlSchemaSequence CreateSequenceElement(Schema.XmlSchema parent, string name) { Schema.XmlSchemaElement element = new Schema.XmlSchemaElement(); element.Name = name; parent.Items.Add(element); Schema.XmlSchemaComplexType type = new Schema.XmlSchemaComplexType(); type.IsMixed = false; Schema.XmlSchemaSequence sequence = new Schema.XmlSchemaSequence(); type.Particle = sequence; element.SchemaType = type; return(sequence); }
private void InferComplexContent(Element el, string ns, bool isNew) { ComplexType ct = ToComplexType(el); ToComplexContentType(ct); int position = 0; bool consumed = false; do { switch (source.NodeType) { case XmlNodeType.Element: Sequence s = PopulateSequence(ct); Choice c = s.Items.Count > 0 ? s.Items [0] as Choice : null; if (c != null) { ProcessLax(c, ns); } else { ProcessSequence(ct, s, ns, ref position, ref consumed, isNew); } source.MoveToContent(); break; case XmlNodeType.Text: case XmlNodeType.CDATA: case XmlNodeType.SignificantWhitespace: MarkAsMixed(ct); source.ReadString(); source.MoveToContent(); break; case XmlNodeType.EndElement: return; // finished case XmlNodeType.None: throw new NotImplementedException("Internal Error: Should not happen."); } } while (true); }
private Schema.XmlSchemaAll CreateElement(Schema.XmlSchemaSequence parent, string name) { Schema.XmlSchemaElement element = new Schema.XmlSchemaElement(); element.MinOccurs = 0; element.MaxOccursString = "unbounded"; element.Name = name; parent.Items.Add(element); Schema.XmlSchemaComplexType type = new Schema.XmlSchemaComplexType(); type.IsMixed = false; Schema.XmlSchemaAll elementAll = new Schema.XmlSchemaAll(); type.Particle = elementAll; element.SchemaType = type; return(elementAll); }
private void InferAsEmptyElement(Element el, string ns, bool isNew) { ComplexType ct = el.SchemaType as ComplexType; if (ct != null) { SimpleModel sm = ct.ContentModel as SimpleModel; if (sm != null) { ToEmptiableSimpleContent(sm, isNew); return; } ComplexModel cm = ct.ContentModel as ComplexModel; if (cm != null) { ToEmptiableComplexContent(cm, isNew); return; } if (ct.Particle != null) { ct.Particle.MinOccurs = 0; } return; } SimpleType st = el.SchemaType as SimpleType; if (st != null) { st = MakeBaseTypeAsEmptiable(st); switch (st.QualifiedName.Namespace) { case XmlSchema.Namespace: case XdtNamespace: el.SchemaTypeName = st.QualifiedName; break; default: el.SchemaType = st; break; } } }
private void InferElement(Element el, string ns, bool isNew) { // Quick check for reference to another definition // (i.e. element ref='...' that should be redirected) if (el.RefName != QName.Empty) { Element body = GetGlobalElement(el.RefName); if (body == null) { body = CreateElement(el.RefName); InferElement(body, ns, true); } else { InferElement(body, ns, isNew); } return; } // Attributes if (source.MoveToFirstAttribute()) { InferAttributes(el, ns, isNew); source.MoveToElement(); } // Content if (source.IsEmptyElement) { InferAsEmptyElement(el, ns, isNew); source.Read(); source.MoveToContent(); } else { InferContent(el, ns, isNew); source.ReadEndElement(); } if (el.SchemaType == null && el.SchemaTypeName == QName.Empty) { el.SchemaTypeName = QNameString; } }
private bool ElementMatches(Element el, string ns) { bool matches = false; if (el.RefName != QName.Empty) { if (el.RefName.Name == source.LocalName && el.RefName.Namespace == source.NamespaceURI) { matches = true; } } else if (el.Name == source.LocalName && ns == source.NamespaceURI) { matches = true; } return(matches); }
/// <summary> /// Register an element with this schema /// </summary> /// <param name="element">The element to register</param> protected void RegisterElement(System.Xml.Schema.XmlSchemaElement element) { if (elements == null) { elements = new List <XmlSchemaElement>(); } // Look to see if element is already registered foreach (XmlSchemaElement e in elements) { if (e.Name == element.Name) { return; } } XmlSchemaElement ele = new XmlSchemaElement(this, null); ele.Load(element); elements.Add(ele); }
private ClrPropertyInfo BuildSimpleTypeTextProperty(XmlSchemaElement parentElement, XmlSchemaSimpleType schemaType) { Debug.Assert(schemaType != null); ClrPropertyInfo textProperty = new ClrPropertyInfo(Constants.SInnerTypePropertyName, string.Empty, Constants.SInnerTypePropertyName, Occurs.One); textProperty.Origin = SchemaOrigin.Text; bool anonymous = schemaType.QualifiedName.IsEmpty; ClrTypeReference typeRef = BuildTypeReference(schemaType, schemaType.QualifiedName, anonymous, true); textProperty.TypeReference = typeRef; if (anonymous && parentElement != null) { //anonymous type, fixed up the name later string idenfitier = localSymbolTable.AddLocalElement(parentElement); localSymbolTable.AddAnonymousType(idenfitier, parentElement, typeRef); } return(textProperty); }
private void WalkSubstitutionGroup(XmlSchemaElement element, XmlSchemaElement leafElement) { //assuming there is no circular reference between substitutionGroups since we already compiled SchemaSet. XmlQualifiedName subsName = element.SubstitutionGroup; XmlSchemaElement head = schemas.GlobalElements[subsName] as XmlSchemaElement; if ((head.Block & XmlSchemaDerivationMethod.Substitution) == 0) { ArrayList groupMembers = null; if (!substitutionGroups.TryGetValue(subsName, out groupMembers)) { groupMembers = new ArrayList(); groupMembers.Add(head); substitutionGroups.Add(subsName, groupMembers); } groupMembers.Add(leafElement); } if (!head.SubstitutionGroup.IsEmpty) { WalkSubstitutionGroup(head, leafElement); } }
private ClrPropertyInfo BuildProperty(XmlSchemaElement elem, bool fromBaseType) { string identifierName = localSymbolTable.AddLocalElement(elem); XmlSchemaType schemaType = elem.ElementSchemaType; XmlQualifiedName schemaTypeName = schemaType.QualifiedName; string schemaName = elem.QualifiedName.Name; string schemaNs = elem.QualifiedName.Namespace; string clrNs = elem.FormResolved() == XmlSchemaForm.Qualified ? configSettings.GetClrNamespace(schemaNs) : string.Empty; SchemaOrigin typeRefOrigin = SchemaOrigin.Fragment; bool isTypeRef = false; bool anonymousType = schemaTypeName.IsEmpty ? true : false; XmlSchemaObject schemaObject = schemaType; ArrayList substitutionMembers = null; if (elem.IsGlobal()) { substitutionMembers = IsSubstitutionGroupHead(elem); schemaTypeName = elem.QualifiedName; isTypeRef = true; typeRefOrigin = SchemaOrigin.Element; schemaObject = schemas.GlobalElements [schemaTypeName]; //For ref, get the element decl SOM object, as nameMappings are keyed off the SOM object anonymousType = false; } ClrTypeReference typeRef = BuildTypeReference(schemaObject, schemaTypeName, anonymousType, true); typeRef.Origin = typeRefOrigin; typeRef.IsTypeRef = isTypeRef; if (anonymousType && !fromBaseType) { //to fixup later. localSymbolTable.AddAnonymousType(identifierName, elem, typeRef); } ClrPropertyInfo propertyInfo = new ClrPropertyInfo(identifierName, schemaNs, schemaName, GetOccurence(elem)); propertyInfo.Origin = SchemaOrigin.Element; propertyInfo.FromBaseType = fromBaseType; propertyInfo.TypeReference = typeRef; propertyInfo.ClrNamespace = clrNs; //SetFixedDefaultValue(elem, propertyInfo); if (substitutionMembers != null) { propertyInfo.SubstitutionMembers = substitutionMembers; } //BuildAnnotationInformation(propertyInfo, elem); return(propertyInfo); //Place it in the element's namespace, maybe element's parent type's namespace? }
private void ProcessSequence(ComplexType ct, Sequence s, string ns, ref int position, ref bool consumed, bool isNew) { for (int i = 0; i < position; i++) { Element iel = s.Items [i] as Element; if (ElementMatches(iel, ns)) { // Sequence element type violation // might happen (might not, but we // cannot backtrack here). So switch // to sequence of choice* here. ProcessLax(ToSequenceOfChoice(s), ns); return; } } if (s.Items.Count <= position) { QName name = new QName(source.LocalName, source.NamespaceURI); Element nel = CreateElement(name); if (laxOccurrence) { nel.MinOccurs = 0; } InferElement(nel, ns, true); if (ns == name.Namespace) { s.Items.Add(nel); } else { Element re = new Element(); if (laxOccurrence) { re.MinOccurs = 0; } re.RefName = name; AddImport(ns, name.Namespace); s.Items.Add(re); } consumed = true; return; } Element el = s.Items [position] as Element; if (el == null) { throw Error(s, String.Format("Target complex type content sequence has an unacceptable type of particle {0}", s.Items [position])); } bool matches = ElementMatches(el, ns); if (matches) { if (consumed) { el.MaxOccursString = "unbounded"; } InferElement(el, source.NamespaceURI, false); source.MoveToContent(); switch (source.NodeType) { case XmlNodeType.None: if (source.NodeType == XmlNodeType.Element) { goto case XmlNodeType.Element; } else if (source.NodeType == XmlNodeType.EndElement) { goto case XmlNodeType.EndElement; } break; case XmlNodeType.Element: ProcessSequence(ct, s, ns, ref position, ref consumed, isNew); break; case XmlNodeType.Text: case XmlNodeType.CDATA: case XmlNodeType.SignificantWhitespace: MarkAsMixed(ct); source.ReadString(); goto case XmlNodeType.None; case XmlNodeType.Whitespace: source.ReadString(); goto case XmlNodeType.None; case XmlNodeType.EndElement: return; default: source.Read(); break; } } else { if (consumed) { position++; consumed = false; ProcessSequence(ct, s, ns, ref position, ref consumed, isNew); } else { ProcessLax(ToSequenceOfChoice(s), ns); } } }
private void InferTextContent(Element el, bool isNew) { string value = source.ReadString(); if (el.SchemaType == null) { if (el.SchemaTypeName == QName.Empty) { // no type information -> infer type if (isNew) { el.SchemaTypeName = InferSimpleType( value); } else { el.SchemaTypeName = QNameString; } return; } switch (el.SchemaTypeName.Namespace) { case XmlSchema.Namespace: case XdtNamespace: // existing primitive type el.SchemaTypeName = InferMergedType( value, el.SchemaTypeName); break; default: ComplexType ct = schemas.GlobalTypes [ el.SchemaTypeName] as ComplexType; // If it is complex, then just set // mixed='true' (type cannot be set.) // If it is simple, then we cannot // make sure that string value is // valid. So just set as xs:string. if (ct != null) { MarkAsMixed(ct); } else { el.SchemaTypeName = QNameString; } break; } return; } // simpleType SimpleType st = el.SchemaType as SimpleType; if (st != null) { // If simple, then (described above) el.SchemaType = null; el.SchemaTypeName = QNameString; return; } // complexType ComplexType ect = el.SchemaType as ComplexType; SimpleModel sm = ect.ContentModel as SimpleModel; if (sm == null) { // - ComplexContent MarkAsMixed(ect); return; } // - SimpleContent SimpleExt se = sm.Content as SimpleExt; if (se != null) { se.BaseTypeName = InferMergedType(value, se.BaseTypeName); } SimpleRst sr = sm.Content as SimpleRst; if (sr != null) { sr.BaseTypeName = InferMergedType(value, sr.BaseTypeName); sr.BaseType = null; } }
private ClrPropertyInfo BuildComplexTypeTextProperty(XmlSchemaElement parentElement, XmlSchemaComplexType schemaType) { Debug.Assert(schemaType != null); Debug.Assert(schemaType.GetContentType() == XmlSchemaContentType.TextOnly); ClrPropertyInfo textProperty = new ClrPropertyInfo(Constants.SInnerTypePropertyName, string.Empty, Constants.SInnerTypePropertyName, Occurs.One); textProperty.Origin = SchemaOrigin.Text; ClrTypeReference typeRef = null; bool anonymous = false; //Could be derived by restriction or extension //If first time extension, make the base simple type as the type reference XmlSchemaType baseType = schemaType.BaseXmlSchemaType; if (baseType is XmlSchemaSimpleType) { typeRef = BuildTypeReference(baseType, baseType.QualifiedName, false, true); anonymous = false; if (!textPropInheritanceTracker.ContainsKey(schemaType)) { textPropInheritanceTracker.Add(schemaType, textProperty); } } else if (schemaType.HasFacetRestrictions()) { //Derived by restriction, represents the content type with restrictions as a local type //Make the base simple type as the type reference so that we know if it is a list, union or atomic XmlSchemaSimpleType st = schemaType.GetBaseSimpleType(); Debug.Assert(st != null); typeRef = BuildTypeReference(st, st.QualifiedName, true, true); typeRef.Validate = true; anonymous = true; //Also get its base complex type and see if we need to override the content property ClrPropertyInfo baseProp = null; if (textPropInheritanceTracker.TryGetValue(baseType, out baseProp)) { textProperty.IsOverride = true; if (!baseProp.IsOverride) { baseProp.IsVirtual = true; } } } else { return(null); } if (anonymous) { //anonymous type, fixed up the name later, treat complex type with restrictions as an anonymous type //because we need to generate a type to encapsualte these restrictions if (parentElement != null) { string identifier = localSymbolTable.AddLocalElement(parentElement); localSymbolTable.AddAnonymousType(identifier, parentElement, typeRef); } else { localSymbolTable.AddComplexRestrictedContentType(schemaType, typeRef); } } textProperty.TypeReference = typeRef; return(textProperty); }
private void TraverseParticle(XmlSchemaParticle particle, XmlSchemaComplexType baseType, ClrContentTypeInfo typeInfo, XmlSchemaDerivationMethod derivationMethod) { if (particleStack == null) { particleStack = new Stack <ParticleData>(); } else { particleStack.Clear(); } if (propertyNameTypeTable == null) { propertyNameTypeTable = new Dictionary <string, ClrPropertyInfo>(); } else { propertyNameTypeTable.Clear(); } XmlSchemaParticle baseParticle = baseType.ContentTypeParticle; ParticleData particleData; GroupingInfo parentGroupInfo = null; StringBuilder regEx = new StringBuilder(); XmlSchemaGroupBase currentGroupBase = null; GroupingInfo currentGroupingInfo = null; int currentIndex = 0; while (true) { // dont interrogate a particle if we are past the end of the list if (currentGroupBase == null || currentIndex <= currentGroupBase.Items.Count) { ParticleType particleType = particle.GetParticleType(); switch (particleType) { case ParticleType.Element: { XmlSchemaElement elem = particle as XmlSchemaElement; ClrPropertyInfo propertyInfo = null; bool fromBaseType = false; if (derivationMethod == XmlSchemaDerivationMethod.Extension && typeInfo.IsDerived) { if (baseParticle.ContainsElement(elem)) { fromBaseType = true; } else if (!typeInfo.InlineBaseType && baseType.ContainsName(elem.QualifiedName)) { typeInfo.InlineBaseType = true; } } propertyInfo = BuildProperty(elem, fromBaseType); regEx.Append(propertyInfo.PropertyName); AppendOccurenceToRegex(propertyInfo, regEx); //Add to parent if (currentGroupingInfo == null) { //Not adding property to propertyNameTypeTable as this case will occur only for pointless groups, so they have just one property BuildAnnotationInformation(propertyInfo, elem, false, false); typeInfo.AddMember(propertyInfo); } else { BuildAnnotationInformation(propertyInfo, elem, currentGroupingInfo.ContentModelType == ContentModelType.Choice, currentGroupingInfo.IsNested); currentGroupingInfo.AddChild(propertyInfo); SetPropertyFlags(propertyInfo, currentGroupingInfo, elem.ElementSchemaType); } break; } case ParticleType.Any: { regEx.Append("any"); XmlSchemaAny any = particle as XmlSchemaAny; if (derivationMethod == XmlSchemaDerivationMethod.Extension && typeInfo.IsDerived) { if (baseParticle.ContainsWildCard(any)) { typeInfo.HasElementWildCard = true; //ANY property in the base type will be reused } } //Note we always create a property info object to keep the original nesting structure in the schema //so it can be used to create a correct FSM; on the other hand, typeInfo.HasElementWildCard will indicate whether //we need to create a property in the resulting object type. ClrWildCardPropertyInfo wcPropertyInfo = BuildAnyProperty(any, !typeInfo.HasElementWildCard); //Add to parent if (currentGroupingInfo == null) { typeInfo.AddMember(wcPropertyInfo); } else { currentGroupingInfo.AddChild(wcPropertyInfo); } if (!typeInfo.HasElementWildCard) { typeInfo.HasElementWildCard = true; } break; } case ParticleType.Sequence: case ParticleType.Choice: case ParticleType.All: regEx.Append("("); if (currentGroupBase != null) { //already there is a group that we are processing, push it on stack to process sub-group particleStack.Push( new ParticleData(currentGroupBase, currentGroupingInfo, currentIndex)); currentIndex = 0; //Re-start index for new group base } parentGroupInfo = currentGroupingInfo; //Assign parent before creating child groupInfo currentGroupBase = particle as XmlSchemaGroupBase; Debug.Assert(currentGroupBase != null); currentGroupingInfo = new GroupingInfo((ContentModelType)((int)particleType), GetOccurence(currentGroupBase)); //Add to parent if (parentGroupInfo == null) { typeInfo.AddMember(currentGroupingInfo); parentGroupInfo = currentGroupingInfo; //Assign first time } else { parentGroupInfo.AddChild(currentGroupingInfo); parentGroupInfo.HasChildGroups = true; currentGroupingInfo.IsNested = true; if (parentGroupInfo.IsRepeating) { currentGroupingInfo.IsRepeating = true; } if (currentGroupingInfo.IsRepeating) { parentGroupInfo.HasRepeatingGroups = true; } } break; } } //Drill down into items if (currentGroupBase != null && currentIndex < currentGroupBase.Items.Count) { // if this isnt the first, then we need a seperator if (currentIndex > 0) { regEx.Append(currentGroupingInfo.ContentModelType == ContentModelType.Choice ? " | " : ", "); } particle = (XmlSchemaParticle)currentGroupBase.Items[currentIndex++]; } else { if (currentGroupBase != null) { regEx.Append(")"); AppendOccurenceToRegex(currentGroupingInfo, regEx); } if (particleStack.Count > 0) { bool childGroupHasRecurringElements = currentGroupingInfo.HasRecurrentElements; bool childGroupHasRepeatingGroups = currentGroupingInfo.HasRepeatingGroups; particleData = particleStack.Pop(); currentGroupBase = particleData.currentGroupBase; currentGroupingInfo = particleData.currentGroupingInfo; currentGroupingInfo.HasRecurrentElements = childGroupHasRecurringElements; currentGroupingInfo.HasRepeatingGroups = childGroupHasRepeatingGroups; currentIndex = particleData.currentIndex; if (currentIndex < currentGroupBase.Items.Count) { particle = (XmlSchemaParticle)currentGroupBase.Items[currentIndex++]; regEx.Append(currentGroupingInfo.ContentModelType == ContentModelType.Choice ? "|" : ", "); } else { // we were already at the end of the parent group, so just continue currentIndex++; //we are off the end of this list } } else { //No more particles to process break; } } } if (regEx.Length != 0) { typeInfo.ContentModelRegEx = regEx.ToString(); } }
private ComplexType ToComplexType(Element el) { QName name = el.SchemaTypeName; XmlSchemaType type = el.SchemaType; // 1. element type is complex. ComplexType ct = type as ComplexType; if (ct != null) { return(ct); } // 2. reference to global complexType. XmlSchemaType globalType = schemas.GlobalTypes [name] as XmlSchemaType; ct = globalType as ComplexType; if (ct != null) { return(ct); } ct = new ComplexType(); el.SchemaType = ct; el.SchemaTypeName = QName.Empty; // 3. base type name is xs:anyType or no specification. // <xs:complexType /> if (name == QNameAnyType) { return(ct); } else if (type == null && name == QName.Empty) { return(ct); } SimpleModel sc = new SimpleModel(); ct.ContentModel = sc; // 4. type is simpleType // -> extension of existing simple type. SimpleType st = type as SimpleType; if (st != null) { SimpleRst scr = new SimpleRst(); scr.BaseType = st; sc.Content = scr; return(ct); } SimpleExt sce = new SimpleExt(); sc.Content = sce; // 5. type name points to primitive type // -> simple extension of a primitive type st = XmlSchemaType.GetBuiltInSimpleType(name); if (st != null) { sce.BaseTypeName = name; return(ct); } // 6. type name points to global simpleType. st = globalType as SimpleType; if (st != null) { sce.BaseTypeName = name; return(ct); } throw Error(el, "Unexpected schema component that contains simpleTypeName that could not be resolved."); }
private void InferAttributes(Element el, string ns, bool isNew) { // Now this element is going to have complexType. // It currently not, then we have to replace it. ComplexType ct = null; SOMList attList = null; Hashtable table = null; do { switch (source.NamespaceURI) { case NamespaceXml: if (schemas.Schemas( NamespaceXml).Count == 0) { IncludeXmlAttributes(); } break; case XmlSchema.InstanceNamespace: if (source.LocalName == "nil") { el.IsNillable = true; } // all other xsi:* atts are ignored continue; case NamespaceXmlns: continue; } if (ct == null) { ct = ToComplexType(el); attList = GetAttributes(ct); table = CollectAttrTable(attList); } QName attrName = new QName( source.LocalName, source.NamespaceURI); Attr attr = table [attrName] as Attr; if (attr == null) { attList.Add(InferNewAttribute( attrName, isNew, ns)); } else { table.Remove(attrName); if (attr.RefName != null && attr.RefName != QName.Empty) { continue; // just a reference } InferMergedAttribute(attr); } } while (source.MoveToNextAttribute()); // mark all attr definitions that did not appear // as optional. if (table != null) { foreach (Attr attr in table.Values) { attr.Use = Use.Optional; } } }
private void BuildNestedTypes(ClrContentTypeInfo typeInfo) { List <AnonymousType> anonymousTypes = localSymbolTable.GetAnonymousTypes(); foreach (AnonymousType at in anonymousTypes) { XmlQualifiedName qname = null; XmlSchemaComplexType complexType = null; XmlSchemaElement elem = at.parentElement; if (elem == null) { //case 1: "dummy" type for text content in a complex type, with restrictions complexType = at.wrappingType; qname = complexType.QualifiedName; } else { //case 2: anonymous type can also be nested under an element qname = elem.QualifiedName; complexType = elem.ElementSchemaType as XmlSchemaComplexType; } if (complexType != null) { if (complexType.GetContentType() == XmlSchemaContentType.TextOnly && complexType.IsDerivedByRestriction()) { //In this case, we take care of the content/text part only. No nesting types exist. ClrSimpleTypeInfo nestedTypeInfo = ClrSimpleTypeInfo .CreateSimpleTypeInfo( complexType); //Generate its "simple type" version to save restrictions nestedTypeInfo.clrtypeName = at.identifier; nestedTypeInfo.clrtypeNs = configSettings.GetClrNamespace(qname.Namespace); nestedTypeInfo.schemaName = qname.Name; nestedTypeInfo.schemaNs = qname.Namespace; nestedTypeInfo.typeOrigin = SchemaOrigin.Fragment; nestedTypeInfo.IsNested = true; BuildAnnotationInformation(nestedTypeInfo, complexType); typeInfo.NestedTypes.Add(nestedTypeInfo); } else { ClrContentTypeInfo nestedTypeInfo = new ClrContentTypeInfo() { Parent = typeInfo }; localSymbolTable.Init(at.identifier); nestedTypeInfo.clrtypeName = at.identifier; nestedTypeInfo.clrtypeNs = configSettings.GetClrNamespace(qname.Namespace); nestedTypeInfo.schemaName = qname.Name; nestedTypeInfo.schemaNs = qname.Namespace; nestedTypeInfo.typeOrigin = SchemaOrigin.Fragment; nestedTypeInfo.IsNested = true; nestedTypeInfo.baseType = BaseType(complexType); BuildProperties(elem, complexType, nestedTypeInfo); BuildNestedTypes(nestedTypeInfo); BuildAnnotationInformation(nestedTypeInfo, complexType); typeInfo.NestedTypes.Add(nestedTypeInfo); } } //Also handle simple types XmlSchemaSimpleType simpleType = null; if (elem != null) { simpleType = elem.ElementSchemaType as XmlSchemaSimpleType; } if (simpleType != null) { ClrSimpleTypeInfo nestedTypeInfo = ClrSimpleTypeInfo.CreateSimpleTypeInfo(simpleType); nestedTypeInfo.clrtypeName = at.identifier; nestedTypeInfo.clrtypeNs = configSettings.GetClrNamespace(qname.Namespace); nestedTypeInfo.schemaName = qname.Name; nestedTypeInfo.schemaNs = qname.Namespace; nestedTypeInfo.typeOrigin = SchemaOrigin.Fragment; nestedTypeInfo.IsNested = true; BuildAnnotationInformation(nestedTypeInfo, simpleType); typeInfo.NestedTypes.Add(nestedTypeInfo); } } }
internal void ElementsToTypes() { bool isRoot = false; int rootElementsCount = schemas.GlobalElements.Count; foreach (XmlSchemaElement elem in schemas.GlobalElements.Values) { SymbolEntry symbol = symbolTable.AddElement(elem); XmlSchemaType schemaType = elem.ElementSchemaType; string xsdNamespace = elem.QualifiedName.Namespace; ClrTypeInfo typeInfo = null; XmlSchemaElement headElement = null; if (!elem.SubstitutionGroup.IsEmpty) { headElement = (XmlSchemaElement)schemas.GlobalElements[elem.SubstitutionGroup]; } if (schemaType.IsGlobal()) { //Global elem with global type, generate wrapper class for the element bool hasBaseContentType = headElement != null && headElement.ElementSchemaType == schemaType; ClrWrapperTypeInfo wtypeInfo = new ClrWrapperTypeInfo(hasBaseContentType); ClrTypeReference typeDef = BuildTypeReference(schemaType, schemaType.QualifiedName, false, true); //Save the fixed/default value of the element wtypeInfo.InnerType = typeDef; typeInfo = wtypeInfo; typeInfo.baseType = headElement; //If element is member of substitutionGroup, add derivation step } else { ClrContentTypeInfo ctypeInfo = new ClrContentTypeInfo(); localSymbolTable.Init(symbol.identifierName); ctypeInfo.baseType = headElement; //If element is member of substitutionGroup, add derivation step BuildProperties(elem, schemaType, ctypeInfo); BuildNestedTypes(ctypeInfo); typeInfo = ctypeInfo; } if (!isRoot) { if (rootElementsCount == 1 || CheckUnhandledAttributes(elem)) { typeInfo.IsRoot = true; isRoot = true; } } typeInfo.IsSubstitutionHead = IsSubstitutionGroupHead(elem) != null; typeInfo.IsAbstract = elem.IsAbstract; typeInfo.clrtypeName = symbol.identifierName; typeInfo.clrtypeNs = symbol.clrNamespace; typeInfo.schemaName = symbol.symbolName; typeInfo.schemaNs = xsdNamespace; typeInfo.typeOrigin = SchemaOrigin.Element; BuildAnnotationInformation(typeInfo, schemaType); binding.Types.Add(typeInfo); } }