Beispiel #1
0
		internal XmlSchemaInfo (IXmlSchemaInfo info)
		{
			isDefault = info.IsDefault;
			isNil = info.IsNil;
			memberType = info.MemberType;
			attr = info.SchemaAttribute;
			elem = info.SchemaElement;
			type = info.SchemaType;
			validity = info.Validity;
		}
 XmlSchemaAttribute FindSchemaObjectForSelectedAttribute(XmlSchemaCompletion schemaForSelectedElement, XmlSchemaElement selectedSchemaElement)
 {
     return(schemaForSelectedElement.FindAttribute(selectedSchemaElement, selectedElement.SelectedAttribute));
 }
Beispiel #3
0
 protected override void Visit(XmlSchemaElement element)
 {
     _elements.Add(element);
 }
Beispiel #4
0
        private DomNodeType GetNodeType(XmlSchemaComplexType complexType, XmlSchemaElement element)
        {
            // get type name
            XmlQualifiedName name = complexType.QualifiedName;

            if (name.IsEmpty) // local type
            {
                name = GetLocalTypeName(element);
            }

            string      typeName = name.ToString();
            DomNodeType nodeType;

            if (!m_nodeTypes.TryGetValue(typeName, out nodeType))
            {
                // build a new complex type and add it to the dictionary
                nodeType = new DomNodeType(typeName);
                m_nodeTypes.Add(typeName, nodeType);

                m_annotations.Add(nodeType, GetAnnotation(complexType));

                DomNodeType      baseType  = null;
                XmlAttributeType valueType = null;

                XmlSchemaComplexType complexBaseType = GetBaseType(complexType);
                if (complexBaseType != null)
                {
                    baseType = GetNodeType(complexBaseType, null);
                }

                XmlSchemaSimpleType simpleBase = complexType.BaseXmlSchemaType as XmlSchemaSimpleType;
                if (simpleBase != null)
                {
                    valueType = GetAttributeType(simpleBase);
                }
                else if (complexType.IsMixed)
                {
                    valueType = s_mixedTextFieldSimpleType;
                }

                WalkParticle(complexType.ContentTypeParticle, nodeType);

                if (valueType != null)
                {
                    XmlAttributeInfo attributeInfo = new XmlAttributeInfo(string.Empty, valueType);
                    nodeType.Define(attributeInfo);
                }

                // get XML attributes
                System.Collections.ICollection attributeUses = complexType.AttributeUses.Values;
                foreach (XmlSchemaAttribute attribute in attributeUses)
                {
                    XmlAttributeType attributeType = GetAttributeType(attribute.AttributeSchemaType);
                    string           fieldName     = GetFieldName(attribute.QualifiedName);
                    XmlAttributeInfo attributeInfo = new XmlAttributeInfo(fieldName, attributeType);

                    if (attribute.DefaultValue != null)
                    {
                        attributeInfo.DefaultValue = attributeType.Convert(attribute.DefaultValue);
                    }

                    m_annotations.Add(attributeInfo, GetAnnotation(attribute));

                    nodeType.Define(attributeInfo);
                }

                if (baseType != null)
                {
                    nodeType.BaseType = baseType;
                }

                nodeType.IsAbstract = complexType.IsAbstract;
            }

            return(nodeType);
        }
Beispiel #5
0
        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();
            }
        }
        public void ParentOffersNoExtension(XmlSchemaElement parentElement, XmlSchemaAttribute extensionAttribute)
        {
            var message = String.Format(CultureInfo.CurrentCulture, Resources.ProblemReporterAttributeParentElementOffersNoExtension, parentElement.QualifiedName, extensionAttribute.QualifiedName);

            _messageReporter.ReportWarning("XSD0010", message);
        }
        public XmlSchemaElement GetSchema(ServerRuleTypeEnum ruleType)
        {
            if (!ruleType.Equals(ServerRuleTypeEnum.OnlineRetention))
            {
                return(null);
            }

            XmlSchemaSimpleType timeUnitType = new XmlSchemaSimpleType();

            XmlSchemaSimpleTypeRestriction restriction = new XmlSchemaSimpleTypeRestriction();

            restriction.BaseTypeName = new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema");

            XmlSchemaEnumerationFacet enumeration = new XmlSchemaEnumerationFacet();

            enumeration.Value = "minutes";
            restriction.Facets.Add(enumeration);

            enumeration       = new XmlSchemaEnumerationFacet();
            enumeration.Value = "hours";
            restriction.Facets.Add(enumeration);

            enumeration       = new XmlSchemaEnumerationFacet();
            enumeration.Value = "weeks";
            restriction.Facets.Add(enumeration);

            enumeration       = new XmlSchemaEnumerationFacet();
            enumeration.Value = "days";
            restriction.Facets.Add(enumeration);

            enumeration       = new XmlSchemaEnumerationFacet();
            enumeration.Value = "months";
            restriction.Facets.Add(enumeration);

            enumeration       = new XmlSchemaEnumerationFacet();
            enumeration.Value = "years";
            restriction.Facets.Add(enumeration);

            timeUnitType.Content = restriction;

            XmlSchemaSimpleType            languageType = new XmlSchemaSimpleType();
            XmlSchemaSimpleTypeRestriction languageEnum = new XmlSchemaSimpleTypeRestriction();

            languageEnum.BaseTypeName = new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema");
            enumeration       = new XmlSchemaEnumerationFacet();
            enumeration.Value = "dicom";
            languageEnum.Facets.Add(enumeration);
            languageType.Content = languageEnum;

            XmlSchemaComplexType type = new XmlSchemaComplexType();

            XmlSchemaAttribute attrib = new XmlSchemaAttribute();

            attrib.Name           = "time";
            attrib.Use            = XmlSchemaUse.Required;
            attrib.SchemaTypeName = new XmlQualifiedName("double", "http://www.w3.org/2001/XMLSchema");
            type.Attributes.Add(attrib);


            attrib            = new XmlSchemaAttribute();
            attrib.Name       = "unit";
            attrib.Use        = XmlSchemaUse.Required;
            attrib.SchemaType = timeUnitType;
            type.Attributes.Add(attrib);

            attrib                = new XmlSchemaAttribute();
            attrib.Name           = "refValue";
            attrib.Use            = XmlSchemaUse.Optional;
            attrib.SchemaTypeName = new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema");
            type.Attributes.Add(attrib);

            attrib            = new XmlSchemaAttribute();
            attrib.Name       = "expressionLanguage";
            attrib.Use        = XmlSchemaUse.Optional;
            attrib.SchemaType = languageType;

            type.Attributes.Add(attrib);
            XmlSchemaElement element = new XmlSchemaElement();

            element.Name       = "online-retention";
            element.SchemaType = type;

            return(element);
        }
Beispiel #8
0
 public static bool IsLocal(this XmlSchemaElement el)
 {
     return(!el.IsGlobal());
 }
Beispiel #9
0
        //<all
        //  id = ID
        //  maxOccurs = 1 : 1
        //  minOccurs = (0 | 1) : 1
        //  {any attributes with non-schema namespace . . .}>
        //  Content: (annotation?, element*)
        //</all>
        internal static XmlSchemaAll Read(XmlSchemaReader reader, ValidationEventHandler h)
        {
            XmlSchemaAll all = new XmlSchemaAll();

            reader.MoveToElement();

            if (reader.NamespaceURI != XmlSchema.Namespace || reader.LocalName != xmlname)
            {
                error(h, "Should not happen :1: XmlSchemaAll.Read, name=" + reader.Name, null);
                reader.SkipToEnd();
                return(null);
            }

            all.LineNumber   = reader.LineNumber;
            all.LinePosition = reader.LinePosition;
            all.SourceUri    = reader.BaseURI;

            //Read Attributes
            while (reader.MoveToNextAttribute())
            {
                if (reader.Name == "id")
                {
                    all.Id = reader.Value;
                }
                else if (reader.Name == "maxOccurs")
                {
                    try
                    {
                        all.MaxOccursString = reader.Value;
                    }
                    catch (Exception e)
                    {
                        error(h, reader.Value + " is an invalid value for maxOccurs", e);
                    }
                }
                else if (reader.Name == "minOccurs")
                {
                    try
                    {
                        all.MinOccursString = reader.Value;
                    }
                    catch (Exception e)
                    {
                        error(h, reader.Value + " is an invalid value for minOccurs", e);
                    }
                }
                else if ((reader.NamespaceURI == "" && reader.Name != "xmlns") || reader.NamespaceURI == XmlSchema.Namespace)
                {
                    error(h, reader.Name + " is not a valid attribute for all", null);
                }
                else
                {
                    XmlSchemaUtil.ReadUnhandledAttribute(reader, all);
                }
            }

            reader.MoveToElement();
            if (reader.IsEmptyElement)
            {
                return(all);
            }

            //Content: (annotation?, element*)
            int level = 1;

            while (reader.ReadNextElement())
            {
                if (reader.NodeType == XmlNodeType.EndElement)
                {
                    if (reader.LocalName != xmlname)
                    {
                        error(h, "Should not happen :2: XmlSchemaAll.Read, name=" + reader.Name, null);
                    }
                    break;
                }
                if (level <= 1 && reader.LocalName == "annotation")
                {
                    level = 2;                          //Only one annotation
                    XmlSchemaAnnotation annotation = XmlSchemaAnnotation.Read(reader, h);
                    if (annotation != null)
                    {
                        all.Annotation = annotation;
                    }
                    continue;
                }
                if (level <= 2 && reader.LocalName == "element")
                {
                    level = 2;
                    XmlSchemaElement element = XmlSchemaElement.Read(reader, h);
                    if (element != null)
                    {
                        all.items.Add(element);
                    }
                    continue;
                }
                reader.RaiseInvalidElementError();
            }
            return(all);
        }
Beispiel #10
0
 public static bool IsGlobal(this XmlSchemaElement el)
 {
     return(el.Parent is XmlSchema);
 }
Beispiel #11
0
        /// <summary>
        /// If the attribute value found references another item in the schema
        /// return this instead of the attribute schema object. For example, if the
        /// user can select the attribute value and the code will work out the schema object pointed to by the ref
        /// or type attribute:
        ///
        /// xs:element ref="ref-name"
        /// xs:attribute type="type-name"
        /// </summary>
        /// <returns>
        /// The <paramref name="attribute"/> if no schema object was referenced.
        /// </returns>
        XmlSchemaObject GetSchemaObjectReferenced(XmlSchemaCompletionData currentSchemaCompletionData, XmlSchemaElement element, XmlSchemaAttribute attribute)
        {
            XmlSchemaObject schemaObject = null;

            if (IsXmlSchemaNamespace(element))
            {
                // Find attribute value.
                //fixme implement
                string attributeValue = "";                // XmlParser.GetAttributeValueAtIndex(xml, index);
                if (attributeValue.Length == 0)
                {
                    return(attribute);
                }

                if (attribute.Name == "ref")
                {
                    schemaObject = FindSchemaObjectReference(attributeValue, currentSchemaCompletionData, element.Name);
                }
                else if (attribute.Name == "type")
                {
                    schemaObject = FindSchemaObjectType(attributeValue, currentSchemaCompletionData, element.Name);
                }
            }

            if (schemaObject != null)
            {
                return(schemaObject);
            }
            return(attribute);
        }
 /// <summary>
 /// Default constructor.
 /// </summary>
 /// <param name="element">The schema element.</param>
 /// <param name="type">The schema type of the object.</param>
 /// <param name="name">The name the element will have.</param>
 /// <param name="typeName">The type name, which can be different from the
 /// schema type name because of TypeNaming conventions.</param>
 /// <param name="parent">The parent of the element.</param>
 public VisitableElementSimpleType(XmlSchemaElement element,
                                   XmlSchemaSimpleType type, string name, string typeName,
                                   BaseSchemaTypedElement parent) : base(element, type, name, typeName, parent)
 {
 }
Beispiel #13
0
    public static void Main()
    {
        XmlSchema schema = new XmlSchema();

        // <xs:element name="cat" type="string"/>
        XmlSchemaElement elementCat = new XmlSchemaElement();

        schema.Items.Add(elementCat);
        elementCat.Name           = "cat";
        elementCat.SchemaTypeName = new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema");

        // <xs:element name="dog" type="string"/>
        XmlSchemaElement elementDog = new XmlSchemaElement();

        schema.Items.Add(elementDog);
        elementDog.Name           = "dog";
        elementDog.SchemaTypeName = new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema");

        // <xs:element name="redDog" substitutionGroup="dog" />
        XmlSchemaElement elementRedDog = new XmlSchemaElement();

        schema.Items.Add(elementRedDog);
        elementRedDog.Name = "redDog";
        elementRedDog.SubstitutionGroup = new XmlQualifiedName("dog");

        // <xs:element name="brownDog" substitutionGroup ="dog" />
        XmlSchemaElement elementBrownDog = new XmlSchemaElement();

        schema.Items.Add(elementBrownDog);
        elementBrownDog.Name = "brownDog";
        elementBrownDog.SubstitutionGroup = new XmlQualifiedName("dog");

        // <xs:element name="pets">
        XmlSchemaElement elementPets = new XmlSchemaElement();

        schema.Items.Add(elementPets);
        elementPets.Name = "pets";

        // <xs:complexType>
        XmlSchemaComplexType complexType = new XmlSchemaComplexType();

        elementPets.SchemaType = complexType;

        // <xs:choice minOccurs="0" maxOccurs="unbounded">
        XmlSchemaChoice choice = new XmlSchemaChoice();

        complexType.Particle   = choice;
        choice.MinOccurs       = 0;
        choice.MaxOccursString = "unbounded";

        // <xs:element ref="cat"/>
        XmlSchemaElement catRef = new XmlSchemaElement();

        choice.Items.Add(catRef);
        catRef.RefName = new XmlQualifiedName("cat");

        // <xs:element ref="dog"/>
        XmlSchemaElement dogRef = new XmlSchemaElement();

        choice.Items.Add(dogRef);
        dogRef.RefName = new XmlQualifiedName("dog");

        XmlSchemaSet schemaSet = new XmlSchemaSet();

        schemaSet.ValidationEventHandler += new ValidationEventHandler(ValidationCallbackOne);
        schemaSet.Add(schema);
        schemaSet.Compile();

        XmlSchema compiledSchema = null;

        foreach (XmlSchema schema1 in schemaSet.Schemas())
        {
            compiledSchema = schema1;
        }

        XmlNamespaceManager nsmgr = new XmlNamespaceManager(new NameTable());

        nsmgr.AddNamespace("xs", "http://www.w3.org/2001/XMLSchema");
        compiledSchema.Write(Console.Out, nsmgr);
    }
Beispiel #14
0
	public void DumpElement (XmlSchemaElement e)
	{
		depth++;

		IndentLine ("**Element**");
		IndentLine ("QualifiedName: " + e.QualifiedName);
		IndentLine ("ElementType:");
		DumpType (e.ElementType);

		depth--;
	}
Beispiel #15
0
 public static IEnumerable <XmlSchemaAttribute> LocalXsdAttributes(this XmlSchemaElement el)
 {
     return(el.SchemaType.LocalXsdAttributes());
 }
Beispiel #16
0
    } //WriteXmlSchemaParticle()

    // XmlSchemaElement
    public static void WriteXmlSchemaElement(XmlSchemaElement element, XmlSchema myXmlSchema, XmlTextWriter myXmlTextWriter)
    {
      myXmlTextWriter.WriteStartElement("element", XmlSchema.Namespace);
      if (element.Name != null)
      {
        myXmlTextWriter.WriteAttributeString("name", element.Name);
      }//if

      if (!element.RefName.IsEmpty)
      {
        myXmlTextWriter.WriteStartAttribute("ref", null);
        myXmlTextWriter.WriteQualifiedName(element.RefName.Name, element.RefName.Namespace);
        myXmlTextWriter.WriteEndAttribute();
      } //if

      if (!element.SchemaTypeName.IsEmpty)
      {
        myXmlTextWriter.WriteStartAttribute("type", null);
        myXmlTextWriter.WriteQualifiedName(element.SchemaTypeName.Name, element.SchemaTypeName.Namespace);
        myXmlTextWriter.WriteEndAttribute();
      } //if

      if (element.SchemaType != null)
      {
        if (element.SchemaType is XmlSchemaComplexType)
          WriteXmlSchemaComplexType((XmlSchemaComplexType)element.SchemaType, myXmlSchema, myXmlTextWriter);
        else
          WriteXmlSchemaSimpleType((XmlSchemaSimpleType)element.SchemaType, myXmlTextWriter);
      } //if
      myXmlTextWriter.WriteEndElement();
    } //WriteXmlSchemaElement()
Beispiel #17
0
 public static IEnumerable <XmlSchemaElement> LocalXsdElements(this XmlSchemaElement el)
 {
     return(el.SchemaType.LocalXsdElements());
 }
Beispiel #18
0
        void ProcessElement(XmlWriter writer, XmlSchemaElement elem, Int32 level, ExpandoObject model, Boolean simple = false)
        {
            if (elem.MaxOccurs > 1 && !simple)
            {
                ProcessArray(writer, elem, model, level);
                return;
            }

            var innerModel = model.GetObject(elem.Name);

            if (innerModel == null)
            {
                if (elem.MinOccurs == 0)
                {
                    return;
                }
            }

            writer.WriteStartElement(elem.Name);
            if (level == 0 && FirstSchema != null)
            {
                writer.WriteAttributeString("xsi", "noNamespaceSchemaLocation", XmlSchema.InstanceNamespace, FirstSchema);
            }


            switch (elem.ElementSchemaType)
            {
            case XmlSchemaComplexType complexType:
                var pi = complexType.Particle as XmlSchemaSequence;
                if (pi != null)
                {
                    if (complexType.AttributeUses != null)
                    {
                        foreach (var an in complexType.AttributeUses.Names)
                        {
                            var attr = complexType.AttributeUses[an as XmlQualifiedName] as XmlSchemaAttribute;
                            WriteAttribute(writer, attr, model);
                        }
                    }
                    foreach (var p in pi?.Items)
                    {
                        switch (p)
                        {
                        case XmlSchemaElement schemaElem:
                            if (simple)
                            {
                                writer.WriteStartElement(schemaElem.Name);
                                WriteSimpleElement(writer, schemaElem, model);
                                writer.WriteEndElement();
                            }
                            else
                            {
                                ProcessElement(writer, schemaElem, level + 1, innerModel as ExpandoObject);
                            }
                            break;

                        case XmlSchemaChoice schemaChoice:
                            WriteElementChoice(writer, schemaChoice, innerModel as ExpandoObject);
                            break;
                        }
                    }
                }
                else if (complexType.ContentModel is XmlSchemaSimpleContent)
                {
                    WriteSimpleElement(writer, elem, model);
                }
                break;

            case XmlSchemaSimpleType simpleType:
                WriteSimpleElement(writer, elem, model);
                break;
            }
            writer.WriteEndElement();
        }
Beispiel #19
0
 public static IEnumerable <XmlSchemaAttribute> XsdAttributesInScope(this XmlSchemaElement el)
 {
     return(el.SchemaType.XsdAttributesInScope());
 }
        public void ParentOffersNoExtension(XmlSchemaComplexType parentComplexType, XmlSchemaElement extensionElement)
        {
            var message = String.Format(CultureInfo.CurrentCulture, Resources.ProblemReporterElementParentComplexTypeOffersNoExtension, parentComplexType.QualifiedName, extensionElement.QualifiedName);

            _messageReporter.ReportWarning("XSD0009", message);
        }
Beispiel #21
0
        //read to dataGridView
        private void button2_Click(object sender, EventArgs e)
        {
            xss = new XmlSchemaSet();
            xss.ValidationEventHandler += ValidationErrorHandler;
            xss.XmlResolver             = new XmlUrlResolver();

            schemas = new XmlSchemas();
            foreach (var fi in diXsd.GetFiles("Passport.xsd")) //Passport.xsd читается полностью
                                                               //разбиение на функции + цикличность?
                                                               //datagridview
            {
                using (var sr = new StreamReader(fi.FullName))
                {
                    xs = XmlSchema.Read(sr, ValidationErrorHandler);
                    xss.Add(xs);
                    schemas.Add(xs);
                }
                MessageBox.Show("Schema " + fi.Name + " read successully ");
            }

            xss.Compile();

            XmlSchemaElement schemaElement = null;

            foreach (XmlSchema schema in xss.Schemas())
            {
                foreach (var sChemaItem in schema.Items)
                {
                    schemaElement = sChemaItem as XmlSchemaElement;
                    if (schemaElement != null)
                    {
                        // MessageBox.Show("ELEMENT: " + schemaElement.Name);

                        // Get the complex type of the element.
                        XmlSchemaComplexType complexType = schemaElement.ElementSchemaType as XmlSchemaComplexType;
                        //  MessageBox.Show("NAME OF COMPLEX TYPE OF " + schemaElement.Name + " = " + complexType.Name);


                        // Get the sequence particle of the complex type.
                        XmlSchemaSequence sequence = complexType.ContentTypeParticle as XmlSchemaSequence;
                        int i = 0;
                        // Iterate over each XmlSchemaElement in the Items collection.
                        foreach (XmlSchemaElement childElement in sequence.Items)
                        {
                            //  MessageBox.Show("ELEMENT OF "+ complexType.Name+" = " + childElement.Name);



                            XmlSchemaComplexType complexType2 = childElement.ElementSchemaType as XmlSchemaComplexType;
                            if (childElement.ElementSchemaType.Name != null)
                            {
                                //     MessageBox.Show("COMPLEX TYPE OF " + childElement.Name + " = " + childElement.ElementSchemaType.Name);
                            }


                            //  MessageBox.Show("NAME OF COMPLEX TYPE OF " + childElement.Name + " = " + complexType2.Name);


                            // DataGridView dataGridView1 = new DataGridView();//Create new grid
                            //dataGridView1.Columns[0].Name = "element";
                            dataGridView1.ColumnCount = 2;
                            // Get the sequence particle of the complex type.

                            XmlSchemaAll all = complexType2.Particle as XmlSchemaAll; // <xsd:all>
                            if (all != null)
                            {
                                dataGridView1.RowCount = all.Items.Count;

                                // Iterate over each XmlSchemaElement in the Items collection.
                                foreach (XmlSchemaElement childElement2 in all.Items)
                                {
                                    if (complexType2.Name != null)
                                    {
                                        //         MessageBox.Show("ELEMENT OF " + complexType2.Name + " = " + childElement2.Name);
                                        dataGridView1.Rows[i].Cells[0].Value = childElement2.Name;
                                        dataGridView1.Rows[i].Cells[1].Value = complexType2.Name;
                                    }
                                    else
                                    {// MessageBox.Show("ELEMENT OF COMPLEX TYPE = " + childElement2.Name);
                                    }

                                    dataGridView1.Rows[i].Cells[0].Value = childElement2.Name;
                                    if (childElement2.ElementSchemaType.TypeCode.ToString() != "None")
                                    {
                                        // MessageBox.Show("TYPE OF " + childElement2.Name + " = " + childElement2.ElementSchemaType.TypeCode);
                                        dataGridView1.Rows[i].Cells[1].Value = childElement2.ElementSchemaType.TypeCode;
                                    }
                                    else
                                    {
                                        dataGridView1.Rows[i].Cells[1].Value = childElement2.ElementSchemaType.Name;
                                    }

                                    i++;
                                }
                                if (complexType2.AttributeUses.Count > 0)
                                {
                                    IDictionaryEnumerator enumerator =
                                        complexType2.AttributeUses.GetEnumerator();

                                    while (enumerator.MoveNext())
                                    {
                                        XmlSchemaAttribute attribute =
                                            (XmlSchemaAttribute)enumerator.Value;

                                        MessageBox.Show("Attribute: " + attribute.Name);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
Beispiel #22
0
        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();
                        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);
                }
            }
        }
Beispiel #23
0
        void ImportSchemasAsClasses(
            string outputdir,
            ICodeGenerator codeGen,
            string fileExtension,
            IList fileNames,
            string ns,
            string uri,
            IList elements)
        {
            XmlSchemas schemasToCompile = new XmlSchemas();
            XmlSchemas userSchemas      = new XmlSchemas();
            string     outputSchemaName = "";
            // Create parent schema
            XmlSchema parent = new XmlSchema();

            foreach (string fileName in fileNames)
            {
                schemasToCompile.Add(ReadSchema(fileName, false));
                userSchemas.Add(ReadSchema(fileName, true));
                outputSchemaName += Path.ChangeExtension(fileName, "").Replace('.', '_');
            }

            Hashtable includeSchemas = new Hashtable();

            foreach (XmlSchema schema in schemasToCompile)
            {
                CollectIncludes(schema, includeSchemas, false);
            }
            Compile(schemasToCompile);

            includeSchemas = new Hashtable();
            foreach (XmlSchema schema in userSchemas)
            {
                CollectIncludes(schema, includeSchemas, true);
            }

            try {
                outputSchemaName = outputSchemaName.Substring(0, outputSchemaName.Length - 1);
                XmlSchemaImporter schemaImporter  = new XmlSchemaImporter(userSchemas);
                CodeCompileUnit   codeCompileUnit = new CodeCompileUnit();
                CodeNamespace     codeNamespace   = new CodeNamespace(ns);
                codeCompileUnit.Namespaces.Add(codeNamespace);
                GenerateVersionComment(codeNamespace);
                XmlCodeExporter codeExporter = new XmlCodeExporter(codeNamespace, codeCompileUnit);
                AddImports(codeNamespace, GetNamespacesForTypes(new Type[] { typeof(XmlAttributeAttribute) }));

                for (int i = 0; i < userSchemas.Count; i++)
                {
                    XmlSchema schema = userSchemas[i];
                    for (int j = 0; j < schema.Items.Count; j++)
                    {
                        object item = schema.Items[j];
                        if (item is XmlSchemaElement)
                        {
                            XmlSchemaElement element = (XmlSchemaElement)item;
                            if (!element.IsAbstract)
                            {
                                if (uri.Length == 0 ||
                                    schema.TargetNamespace == uri)
                                {
                                    bool found;
                                    if (elements.Count == 0)
                                    {
                                        found = true;
                                    }
                                    else
                                    {
                                        found = false;
                                        foreach (string e in elements)
                                        {
                                            if (e == element.Name)
                                            {
                                                found = true;
                                                break;
                                            }
                                        }
                                    }
                                    if (found)
                                    {
                                        XmlTypeMapping xmlTypeMapping = schemaImporter.ImportTypeMapping(new XmlQualifiedName(element.Name, schema.TargetNamespace));
                                        codeExporter.ExportTypeMapping(xmlTypeMapping);
                                    }
                                }
                            }
                        }
                    }
                }

                CodeTypeDeclarationCollection classes = codeNamespace.Types;
                if (classes == null || classes.Count == 0)
                {
                    Console.WriteLine(Res.GetString(Res.NoClassesGenerated));
                }
                else
                {
                    TextWriter writer = CreateOutputWriter(outputdir, outputSchemaName, fileExtension);
                    codeGen.GenerateCodeFromCompileUnit(codeCompileUnit, writer, null);
                    writer.Close();
                }
            }
            catch (Exception e) {
                throw new InvalidOperationException(Res.GetString(Res.ErrGenerateClassesForSchema, outputSchemaName), e);
            }
        }
Beispiel #24
0
        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 Write46_XmlSchemaElement(XmlSchemaElement o)
        {
            if ((object)o == null)
            {
                return;
            }
            System.Type t = o.GetType();
            WriteStartElement("element");
            WriteAttribute(@"id", @"", o.Id);
            WriteAttribute("minOccurs", "", XmlConvert.ToString(o.MinOccurs));
            WriteAttribute("maxOccurs", "", o.MaxOccurs == decimal.MaxValue ? "unbounded" : XmlConvert.ToString(o.MaxOccurs));
            if (((bool)o.@IsAbstract) != false)
            {
                WriteAttribute(@"abstract", @"", XmlConvert.ToString((bool)((bool)o.@IsAbstract)));
            }
            WriteAttribute(@"block", @"", Write11_XmlSchemaDerivationMethod(o.BlockResolved));
            WriteAttribute(@"default", @"", o.DefaultValue);
            WriteAttribute(@"final", @"", Write11_XmlSchemaDerivationMethod(o.FinalResolved));
            WriteAttribute(@"fixed", @"", o.FixedValue);
            if (o.Parent != null && !(o.Parent is XmlSchema))
            {
                if (o.QualifiedName != null && !o.QualifiedName.IsEmpty && o.QualifiedName.Namespace != null && o.QualifiedName.Namespace.Length != 0)
                {
                    WriteAttribute(@"form", @"", "qualified");
                }
                else
                {
                    WriteAttribute(@"form", @"", "unqualified");
                }
            }
            if (o.Name != null && o.Name.Length != 0)
            {
                WriteAttribute(@"name", @"", o.Name);
            }
            if (o.IsNillable)
            {
                WriteAttribute(@"nillable", @"", XmlConvert.ToString(o.IsNillable));
            }
            if (!o.SubstitutionGroup.IsEmpty)
            {
                WriteAttribute("substitutionGroup", "", o.SubstitutionGroup);
            }
            if (!o.RefName.IsEmpty)
            {
                WriteAttribute("ref", "", o.RefName);
            }
            else if (!o.SchemaTypeName.IsEmpty)
            {
                WriteAttribute("type", "", o.SchemaTypeName);
            }

            WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o);
            Write5_XmlSchemaAnnotation(o.Annotation);
            if (o.SchemaType is XmlSchemaComplexType)
            {
                Write35_XmlSchemaComplexType((XmlSchemaComplexType)o.SchemaType);
            }
            else if (o.SchemaType is XmlSchemaSimpleType)
            {
                Write9_XmlSchemaSimpleType((XmlSchemaSimpleType)o.SchemaType);
            }
            WriteSortedItems(o.Constraints);
            WriteEndElement();
        }
Beispiel #26
0
        private void WalkParticle(XmlSchemaParticle particle, DomNodeType nodeType)
        {
            XmlSchemaElement element = particle as XmlSchemaElement;

            if (element != null)
            {
                XmlSchemaSimpleType simpleType = element.ElementSchemaType as XmlSchemaSimpleType;
                if (simpleType != null &&
                    element.MaxOccurs == 1)
                {
                    bool             forceSerialize = element.MinOccurs == 1;
                    XmlAttributeType attributeType  = GetAttributeType(simpleType);
                    string           fieldName      = GetFieldName(element.QualifiedName);
                    XmlAttributeInfo attributeInfo  = new XmlAttributeInfo(fieldName, attributeType, forceSerialize);

                    nodeType.Define(attributeInfo);
                    m_annotations.Add(attributeInfo, GetAnnotation(element));

                    attributeInfo.IsElement = true;

                    if (element.DefaultValue != null)
                    {
                        if (element.FixedValue != null)
                        {
                            throw new InvalidOperationException(string.Format("Schema element {0} cannot have both a default value and a fixed value", element.QualifiedName));
                        }
                        attributeInfo.DefaultValue = attributeType.Convert(element.DefaultValue);
                    }
                    else if (element.FixedValue != null)
                    {
                        attributeInfo.DefaultValue = attributeType.Convert(element.FixedValue);
                    }
                }
                else
                {
                    DomNodeType childNodeType = null;
                    if (simpleType != null)
                    {
                        bool firstTime;
                        childNodeType = WrapSimpleType(simpleType, out firstTime);

                        // The collada.xsd's ListOfUInts element breaks the generated Schema.cs file otherwise.
                        if (firstTime)
                        {
                            // Add the value attribute
                            XmlAttributeType valueAttributeType = GetAttributeType(simpleType);
                            var valueAttributeInfo = new XmlAttributeInfo(string.Empty, valueAttributeType);
                            childNodeType.Define(valueAttributeInfo);
                        }
                    }
                    else
                    {
                        XmlSchemaComplexType complexType = element.ElementSchemaType as XmlSchemaComplexType;
                        if (complexType != null)
                        {
                            childNodeType = GetNodeType(complexType, element);
                        }
                    }

                    if (childNodeType != null)
                    {
                        int minOccurs = (int)Math.Min(element.MinOccurs, Int32.MaxValue);
                        int maxOccurs = (int)Math.Min(element.MaxOccurs, Int32.MaxValue);

                        if (particle.Parent is XmlSchemaChoice)
                        {
                            var parent = (XmlSchemaChoice)particle.Parent;
                            if (parent.MinOccurs != 1)
                            {
                                minOccurs = (int)Math.Min(Math.Max(element.MinOccurs, parent.MinOccurs), Int32.MaxValue);
                            }
                            if (parent.MaxOccurs != 1)
                            {
                                maxOccurs = (int)Math.Min(Math.Max(element.MaxOccurs, parent.MaxOccurs), Int32.MaxValue);
                            }
                        }
                        else if (particle.Parent is XmlSchemaSequence)
                        {
                            var parent = (XmlSchemaSequence)particle.Parent;
                            if (parent.MinOccurs != 1)
                            {
                                minOccurs = (int)Math.Min(Math.Max(element.MinOccurs, parent.MinOccurs), Int32.MaxValue);
                            }
                            if (parent.MaxOccurs != 1)
                            {
                                maxOccurs = (int)Math.Min(Math.Max(element.MaxOccurs, parent.MaxOccurs), Int32.MaxValue);
                            }
                        }

                        ChildInfo childInfo = new ChildInfo(GetFieldName(element.QualifiedName), childNodeType, maxOccurs > 1);

                        if ((minOccurs > 0 || maxOccurs < Int32.MaxValue) &&
                            minOccurs <= maxOccurs)
                        {
                            childInfo.AddRule(new ChildCountRule(minOccurs, maxOccurs));
                        }

                        // Check for substitution groups
                        if (!element.RefName.IsEmpty)
                        {
                            m_refElements.Add(childInfo, element.RefName);
                        }

                        nodeType.Define(childInfo);
                        m_annotations.Add(childInfo, GetAnnotation(element));
                    }
                }
            }
            else
            {
                // handle xs:all, xs:sequence and xs:choice
                XmlSchemaGroupBase grp = particle as XmlSchemaSequence;
                if (grp == null)
                {
                    grp = particle as XmlSchemaChoice;
                }
                if (grp == null)
                {
                    grp = particle as XmlSchemaAll;
                }

                if (grp != null)
                {
                    foreach (XmlSchemaParticle subParticle in grp.Items)
                    {
                        WalkParticle(subParticle, nodeType);
                    }
                }
            }
        }
        private void ExportClassDataContract(ClassDataContract classDataContract, XmlSchema schema)
        {
            XmlSchemaComplexType type = new XmlSchemaComplexType();

            type.Name = classDataContract.StableName.Name;
            schema.Items.Add(type);
            XmlElement genericInfoElement = null;

            if (classDataContract.UnderlyingType.IsGenericType)
            {
                genericInfoElement = ExportGenericInfo(classDataContract.UnderlyingType, Globals.GenericTypeLocalName, Globals.SerializationNamespace);
            }

            XmlSchemaSequence rootSequence = new XmlSchemaSequence();

            for (int i = 0; i < classDataContract.Members.Count; i++)
            {
                DataMember dataMember = classDataContract.Members[i];

                XmlSchemaElement element = new XmlSchemaElement();
                element.Name = dataMember.Name;
                XmlElement   actualTypeElement  = null;
                DataContract memberTypeContract = _dataContractSet.GetMemberTypeDataContract(dataMember);
                if (CheckIfMemberHasConflict(dataMember))
                {
                    element.SchemaTypeName = AnytypeQualifiedName;
                    actualTypeElement      = ExportActualType(memberTypeContract.StableName);
                    SchemaHelper.AddSchemaImport(memberTypeContract.StableName.Namespace, schema);
                }
                else
                {
                    SetElementType(element, memberTypeContract, schema);
                }
                SchemaHelper.AddElementForm(element, schema);
                if (dataMember.IsNullable)
                {
                    element.IsNillable = true;
                }
                if (!dataMember.IsRequired)
                {
                    element.MinOccurs = 0;
                }

                element.Annotation = GetSchemaAnnotation(actualTypeElement, ExportSurrogateData(dataMember), ExportEmitDefaultValue(dataMember));
                rootSequence.Items.Add(element);
            }

            XmlElement isValueTypeElement = null;

            if (classDataContract.BaseContract != null)
            {
                XmlSchemaComplexContentExtension extension = CreateTypeContent(type, classDataContract.BaseContract.StableName, schema);
                extension.Particle = rootSequence;
                if (classDataContract.IsReference && !classDataContract.BaseContract.IsReference)
                {
                    AddReferenceAttributes(extension.Attributes, schema);
                }
            }
            else
            {
                type.Particle = rootSequence;
                if (classDataContract.IsValueType)
                {
                    isValueTypeElement = GetAnnotationMarkup(IsValueTypeName, XmlConvert.ToString(classDataContract.IsValueType), schema);
                }
                if (classDataContract.IsReference)
                {
                    AddReferenceAttributes(type.Attributes, schema);
                }
            }
            type.Annotation = GetSchemaAnnotation(genericInfoElement, ExportSurrogateData(classDataContract), isValueTypeElement);
        }
Beispiel #28
0
        public static void Main(string[] args)
        {
            // Create <xsd:schema>
            XmlSchema Schema = new XmlSchema();

            // Create <xsd:element name="Users"/>
            XmlSchemaElement elementUsers = new XmlSchemaElement();

            elementUsers.Name = "Users";

            /* elementUsers.MinOccurs = 0;
             * elementUsers.MaxOccurs = 1;*/
            Schema.Items.Add(elementUsers);

            // Create <xsd:complexType>
            XmlSchemaComplexType tblUsers = new XmlSchemaComplexType();

            elementUsers.SchemaType = tblUsers;

            /*XmlSchemaChoice Choice = new XmlSchemaChoice();
             * Choice.MinOccurs = 0;
             * Choice.MaxOccursString = "unbounded";
             * elementUsers.Items.Add(Choice);*/

            // Create <xsd:sequence>
            XmlSchemaSequence seq0 = new XmlSchemaSequence();

            tblUsers.Particle = seq0;

            // Create <xsd:element name="User"/>
            XmlSchemaElement elementUser = new XmlSchemaElement();

            elementUser.Name = "User";
            seq0.Items.Add(elementUser);


            // Create <xsd:complexType>
            XmlSchemaComplexType tblUser = new XmlSchemaComplexType();

            elementUser.SchemaType = tblUser;

            // Create <xsd:sequence>
            XmlSchemaSequence seq = new XmlSchemaSequence();

            tblUser.Particle = seq;

            // Create <xsd:element name="Team" type="xsd:string"/>
            XmlSchemaElement elementTeam = new XmlSchemaElement();

            elementTeam.Name           = "Team";
            elementTeam.SchemaTypeName = new XmlQualifiedName(
                "string", "http://www.w3.org/2001/XMLSchema");
            seq.Items.Add(elementTeam);

            // Create <xsd:element name="elementCountry" type="xsd:CountryList"/>
            XmlSchemaElement elementCountry = new XmlSchemaElement();

            elementCountry.Name           = "Country";
            elementCountry.SchemaTypeName = new XmlQualifiedName(
                "CountryList");
            seq.Items.Add(elementCountry);

            // Create <xsd:element name="elementProject" type="xsd:string"/>
            XmlSchemaElement elementProject = new XmlSchemaElement();

            elementProject.Name           = "Project";
            elementProject.SchemaTypeName = new XmlQualifiedName(
                "string", "http://www.w3.org/2001/XMLSchema");
            seq.Items.Add(elementProject);

            // Create <xsd:element name="elementRegDate" type="xsd:date"/>
            XmlSchemaElement elementRegDate = new XmlSchemaElement();

            elementRegDate.Name           = "Project";
            elementRegDate.SchemaTypeName = new XmlQualifiedName(
                "date", "http://www.w3.org/2001/XMLSchema");
            seq.Items.Add(elementRegDate);

            // Create <xsd:element name="AvgScore" type="xsd:float"/>
            XmlSchemaElement elementAvgScore = new XmlSchemaElement();

            elementAvgScore.Name           = "AvgScore";
            elementAvgScore.SchemaTypeName = new XmlQualifiedName(
                "float", "http://www.w3.org/2001/XMLSchema");
            seq.Items.Add(elementAvgScore);

            // Create <xsd:element name="AllScore" type="xsd:int"/>
            XmlSchemaElement elementAllScore = new XmlSchemaElement();

            elementAllScore.Name           = "AllScore";
            elementAllScore.SchemaTypeName = new XmlQualifiedName(
                "int", "http://www.w3.org/2001/XMLSchema");
            seq.Items.Add(elementAllScore);

            // Create <xsd:attribute name="UserID" type="xsd:int" use="required"/>
            XmlSchemaAttribute attributeUserID = new XmlSchemaAttribute();

            attributeUserID.Name           = "UserID";
            attributeUserID.SchemaTypeName = new XmlQualifiedName(
                "int", "http://www.w3.org/2001/XMLSchema");
            attributeUserID.Use = XmlSchemaUse.Required;
            tblUser.Attributes.Add(attributeUserID);

            // Create <xsd:attribute name="UserName" type="xsd:string" use="required"/>
            XmlSchemaAttribute attributeUserName = new XmlSchemaAttribute();

            attributeUserName.Name           = "UserName";
            attributeUserName.SchemaTypeName = new XmlQualifiedName(
                "string", "http://www.w3.org/2001/XMLSchema");
            attributeUserName.Use = XmlSchemaUse.Required;
            tblUser.Attributes.Add(attributeUserName);


            string[] Countries = new string[]
            {
                "UNITED STATES", "FRANCE", "GERMANY", "JAPAN", "UNITED KINGDOM", "CANADA", "BRAZIL",
                "ITALY", "AUSTRALIA", "SPAIN", "NETHERLANDS", "CHINA", "CZECH REPUBLIC", "POLAND",
                "BELGIUM", "RUSSIAN FEDERATION", "INDIA", "FINLAND", "TAIWAN", "DENMARK", "SWEDEN",
                "SWITZERLAND", "HUNGARY", "AUSTRIA", "NORWAY", "PORTUGAL", "ARGENTINA", "TURKEY",
                "MEXICO", "ISRAEL", "HONG KONG", "ROMANIA", "IRELAND", "NEW ZEALAND", "SLOVAKIA",
                "SOUTH AFRICA", "THAILAND", "GREECE", "UKRAINE", "MALAYSIA", "BULGARIA", "SINGAPORE",
                "CROATIA", "KOREA, REPUBLIC OF", "VENEZUELA", "CHILE", "COLOMBIA", "PHILIPPINES",
                "SLOVENIA", "INDONESIA"
            };

            XmlSchemaSimpleType CountryList = new XmlSchemaSimpleType();

            CountryList.Name = "CountryList";
            //elementCountry.SchemaType = CountryList;
            Schema.Items.Add(CountryList);

            // Create <xsd:restriction base="xsd:string">
            XmlSchemaSimpleTypeRestriction restriction = new XmlSchemaSimpleTypeRestriction();

            restriction.BaseTypeName = new XmlQualifiedName(
                "string", "http://www.w3.org/2001/XMLSchema");
            CountryList.Content = restriction;

            // Create three <xsd:enumeration...>
            foreach (string Country in Countries)
            {
                XmlSchemaEnumerationFacet e = new XmlSchemaEnumerationFacet();
                e.Value = Country;
                restriction.Facets.Add(e);
            }


            // Compile the schema in memory, to check syntax and semantics
            Schema.Compile(new ValidationEventHandler(MyHandler));

            // Display schema on the screen
            Schema.Write(Console.Out);
            Console.WriteLine("\nSchema has been written to console");

            // Also write schema to "Users.xsd"
            FileStream fs = new FileStream("Users.xsd",
                                           FileMode.Create, FileAccess.Write);

            Schema.Write(fs);
            Console.WriteLine("Schema has been written to file Users.xsd");

            Console.Write("Press any key to exit . . . ");
            Console.ReadKey();
        }
        private void ExportCollectionDataContract(CollectionDataContract collectionDataContract, XmlSchema schema)
        {
            XmlSchemaComplexType type = new XmlSchemaComplexType();

            type.Name = collectionDataContract.StableName.Name;
            schema.Items.Add(type);
            XmlElement genericInfoElement = null, isDictionaryElement = null;

            if (collectionDataContract.UnderlyingType.IsGenericType && CollectionDataContract.IsCollectionDataContract(collectionDataContract.UnderlyingType))
            {
                genericInfoElement = ExportGenericInfo(collectionDataContract.UnderlyingType, Globals.GenericTypeLocalName, Globals.SerializationNamespace);
            }
            if (collectionDataContract.IsDictionary)
            {
                isDictionaryElement = ExportIsDictionary();
            }
            type.Annotation = GetSchemaAnnotation(isDictionaryElement, genericInfoElement, ExportSurrogateData(collectionDataContract));

            XmlSchemaSequence rootSequence = new XmlSchemaSequence();

            XmlSchemaElement element = new XmlSchemaElement();

            element.Name            = collectionDataContract.ItemName;
            element.MinOccurs       = 0;
            element.MaxOccursString = Globals.OccursUnbounded;
            if (collectionDataContract.IsDictionary)
            {
                ClassDataContract    keyValueContract = collectionDataContract.ItemContract as ClassDataContract;
                XmlSchemaComplexType keyValueType     = new XmlSchemaComplexType();
                XmlSchemaSequence    keyValueSequence = new XmlSchemaSequence();
                foreach (DataMember dataMember in keyValueContract.Members)
                {
                    XmlSchemaElement keyValueElement = new XmlSchemaElement();
                    keyValueElement.Name = dataMember.Name;
                    SetElementType(keyValueElement, _dataContractSet.GetMemberTypeDataContract(dataMember), schema);
                    SchemaHelper.AddElementForm(keyValueElement, schema);
                    if (dataMember.IsNullable)
                    {
                        keyValueElement.IsNillable = true;
                    }
                    keyValueElement.Annotation = GetSchemaAnnotation(ExportSurrogateData(dataMember));
                    keyValueSequence.Items.Add(keyValueElement);
                }
                keyValueType.Particle = keyValueSequence;
                element.SchemaType    = keyValueType;
            }
            else
            {
                if (collectionDataContract.IsItemTypeNullable)
                {
                    element.IsNillable = true;
                }
                DataContract itemContract = _dataContractSet.GetItemTypeDataContract(collectionDataContract);
                SetElementType(element, itemContract, schema);
            }
            SchemaHelper.AddElementForm(element, schema);
            rootSequence.Items.Add(element);

            type.Particle = rootSequence;

            if (collectionDataContract.IsReference)
            {
                AddReferenceAttributes(type.Attributes, schema);
            }
        }
 private void WriteXMLForCultures(CultureInfo[] cultures)
 {
     StreamWriter writer = File.CreateText("CultureSchema.xml");		
     XmlSchema schema;
     XmlSchemaElement element;
     XmlSchemaComplexType complexType;
     XmlSchemaSequence sequence;
     schema = new XmlSchema();
     element = new XmlSchemaElement();
     schema.Items.Add(element);
     element.Name = "Table";
     complexType = new XmlSchemaComplexType();
     element.SchemaType = complexType;
     sequence = new XmlSchemaSequence();
     complexType.Particle = sequence;
     element = new XmlSchemaElement();
     element.Name = "CultureName";
     element.SchemaTypeName = new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema");
     sequence.Items.Add(element);
     schema.Compile(new ValidationEventHandler(ValidationCallbackOne));
     schema.Write(writer);
     writer.Close();     
     writer = File.CreateText("CultureData.xml");
     XmlTextWriter myXmlTextWriter = new XmlTextWriter(writer);
     myXmlTextWriter.Formatting = Formatting.Indented;
     myXmlTextWriter.WriteStartElement("NewDataSet");
     for(int j=0; j<cultures.Length; j++)
     {
         myXmlTextWriter.WriteStartElement("Table");
         myXmlTextWriter.WriteElementString("CultureName", cultures[j].LCID.ToString());
         myXmlTextWriter.WriteEndElement();
     }
     myXmlTextWriter.WriteEndElement();
     myXmlTextWriter.Flush();
     myXmlTextWriter.Close();
 }
    public static void Main()
    {
        XmlSchema schema = new XmlSchema();

        // <xs:complexType name="phoneNumber">
        XmlSchemaComplexType phoneNumber = new XmlSchemaComplexType();

        phoneNumber.Name = "phoneNumber";

        // <xs:sequence>
        XmlSchemaSequence phoneNumberSequence = new XmlSchemaSequence();

        // <xs:element name="areaCode"/>
        XmlSchemaElement areaCode1 = new XmlSchemaElement();

        areaCode1.MinOccurs       = 0;
        areaCode1.MaxOccursString = "1";
        areaCode1.Name            = "areaCode";
        phoneNumberSequence.Items.Add(areaCode1);

        // <xs:element name="prefix"/>
        XmlSchemaElement prefix1 = new XmlSchemaElement();

        prefix1.MinOccurs       = 1;
        prefix1.MaxOccursString = "1";
        prefix1.Name            = "prefix";
        phoneNumberSequence.Items.Add(prefix1);

        // <xs:element name="number"/>
        XmlSchemaElement number1 = new XmlSchemaElement();

        number1.MinOccurs       = 1;
        number1.MaxOccursString = "1";
        number1.Name            = "number";
        phoneNumberSequence.Items.Add(number1);

        phoneNumber.Particle = phoneNumberSequence;

        schema.Items.Add(phoneNumber);

        // <xs:complexType name="localPhoneNumber">
        XmlSchemaComplexType localPhoneNumber = new XmlSchemaComplexType();

        localPhoneNumber.Name = "localPhoneNumber";

        // <xs:complexContent>
        XmlSchemaComplexContent complexContent = new XmlSchemaComplexContent();

        // <xs:restriction base="phoneNumber">
        XmlSchemaComplexContentRestriction restriction = new XmlSchemaComplexContentRestriction();

        restriction.BaseTypeName = new XmlQualifiedName("phoneNumber", "");

        // <xs:sequence>
        XmlSchemaSequence sequence2 = new XmlSchemaSequence();

        // <xs:element name="areaCode" minOccurs="0"/>
        XmlSchemaElement areaCode2 = new XmlSchemaElement();

        areaCode2.MinOccurs       = 0;
        areaCode2.MaxOccursString = "1";
        areaCode2.Name            = "areaCode";
        sequence2.Items.Add(areaCode2);

        // <xs:element name="prefix"/>
        XmlSchemaElement prefix2 = new XmlSchemaElement();

        prefix2.MinOccurs       = 1;
        prefix2.MaxOccursString = "1";
        prefix2.Name            = "prefix";
        sequence2.Items.Add(prefix2);

        // <xs:element name="number"/>
        XmlSchemaElement number2 = new XmlSchemaElement();

        number2.MinOccurs       = 1;
        number2.MaxOccursString = "1";
        number2.Name            = "number";
        sequence2.Items.Add(number2);

        restriction.Particle          = sequence2;
        complexContent.Content        = restriction;
        localPhoneNumber.ContentModel = complexContent;

        schema.Items.Add(localPhoneNumber);

        XmlSchemaSet schemaSet = new XmlSchemaSet();

        schemaSet.ValidationEventHandler += new ValidationEventHandler(ValidationCallbackOne);
        schemaSet.Add(schema);
        schemaSet.Compile();

        XmlSchema compiledSchema = null;

        foreach (XmlSchema schema1 in schemaSet.Schemas())
        {
            compiledSchema = schema1;
        }

        XmlNamespaceManager nsmgr = new XmlNamespaceManager(new NameTable());

        nsmgr.AddNamespace("xs", "http://www.w3.org/2001/XMLSchema");
        compiledSchema.Write(Console.Out, nsmgr);
    }
Beispiel #32
0
	public void DumpElementNoRecurse (XmlSchemaElement e)
	{
		depth++;

		IndentLine ("**Element**");
		IndentLine ("QualifiedName: " + e.QualifiedName);

		depth--;
	}
Beispiel #33
0
 public bool Test(XmlSchemaElement el)
 {
     return(true);
 }
Beispiel #34
0
    } //WriteExample()


    // Write some example elements
    public static void WriteExampleElement(XmlSchemaElement element, 
                                           XmlSchema myXmlSchema, 
                                           XmlTextWriter myXmlTextWriter)
    {
      myXmlTextWriter.WriteStartElement(element.QualifiedName.Name, element.QualifiedName.Namespace);
      if (element.ElementType is XmlSchemaComplexType)
      {
        XmlSchemaComplexType type = (XmlSchemaComplexType)element.ElementType;
        if (type.ContentModel != null)
        {
          Console.WriteLine("Not Implemented for this ContentModel");
        } //if
        WriteExampleAttributes(type.Attributes, myXmlSchema, myXmlTextWriter);
        WriteExampleParticle(type.Particle, myXmlSchema, myXmlTextWriter);
      } //if
      else
      {
        WriteExampleValue(element.ElementType, myXmlTextWriter);
      } //else

      myXmlTextWriter.WriteEndElement();
    } //WriteExampleElement()
Beispiel #35
0
        static void Main()
        {
            // The XML document to deserialize into the XmlSerializer object.
            XmlReader reader = XmlReader.Create("contosoBooks.xml");

            // The XmlSerializer object.
            XmlSerializer serializer = new XmlSerializer(typeof(ContosoBooks));
            ContosoBooks  books      = (ContosoBooks)serializer.Deserialize(reader);

            // The XmlSchemaSet object containing the schema used to validate the XML document.
            XmlSchemaSet schemaSet = new XmlSchemaSet();

            schemaSet.Add("http://www.contoso.com/books", "contosoBooks.xsd");

            // The XmlNamespaceManager object used to handle namespaces.
            XmlNamespaceManager manager = new XmlNamespaceManager(reader.NameTable);

            // Assign a ValidationEventHandler to handle schema validation warnings and errors.
            XmlSchemaValidator validator = new XmlSchemaValidator(reader.NameTable, schemaSet, manager, XmlSchemaValidationFlags.None);

            validator.ValidationEventHandler += new ValidationEventHandler(SchemaValidationEventHandler);

            // Initialize the XmlSchemaValidator object.
            validator.Initialize();

            // Validate the bookstore element, verify that all required attributes are present
            // and prepare to validate child content.
            validator.ValidateElement("bookstore", "http://www.contoso.com/books", null);
            validator.GetUnspecifiedDefaultAttributes(new ArrayList());
            validator.ValidateEndOfAttributes(null);

            // Get the next exptected element in the bookstore context.
            XmlSchemaParticle[] particles   = validator.GetExpectedParticles();
            XmlSchemaElement    nextElement = particles[0] as XmlSchemaElement;

            Console.WriteLine("Expected Element: '{0}'", nextElement.Name);

            foreach (BookType book in books.Book)
            {
                // Validate the book element.
                validator.ValidateElement("book", "http://www.contoso.com/books", null);

                // Get the exptected attributes for the book element.
                Console.Write("\nExpected attributes: ");
                XmlSchemaAttribute[] attributes = validator.GetExpectedAttributes();
                foreach (XmlSchemaAttribute attribute in attributes)
                {
                    Console.Write("'{0}' ", attribute.Name);
                }
                Console.WriteLine();

                // Validate the genre attribute and display its post schema validation information.
                if (book.Genre != null)
                {
                    validator.ValidateAttribute("genre", "", book.Genre, schemaInfo);
                }
                DisplaySchemaInfo();

                // Validate the publicationdate attribute and display its post schema validation information.
                if (book.PublicationDate != null)
                {
                    validator.ValidateAttribute("publicationdate", "", dateTimeGetter(book.PublicationDate), schemaInfo);
                }
                DisplaySchemaInfo();

                // Validate the ISBN attribute and display its post schema validation information.
                if (book.Isbn != null)
                {
                    validator.ValidateAttribute("ISBN", "", book.Isbn, schemaInfo);
                }
                DisplaySchemaInfo();

                // After validating all the attributes for the current element with ValidateAttribute method,
                // you must call GetUnspecifiedDefaultAttributes to validate the default attributes.
                validator.GetUnspecifiedDefaultAttributes(new ArrayList());

                // Verify that all required attributes of the book element are present
                // and prepare to validate child content.
                validator.ValidateEndOfAttributes(null);

                // Validate the title element and its content.
                validator.ValidateElement("title", "http://www.contoso.com/books", null);
                validator.ValidateEndElement(null, book.Title);

                // Validate the author element, verify that all required attributes are present
                // and prepare to validate child content.
                validator.ValidateElement("author", "http://www.contoso.com/books", null);
                validator.GetUnspecifiedDefaultAttributes(new ArrayList());
                validator.ValidateEndOfAttributes(null);

                if (book.Author.Name != null)
                {
                    // Validate the name element and its content.
                    validator.ValidateElement("name", "http://www.contoso.com/books", null);
                    validator.ValidateEndElement(null, book.Author.Name);
                }

                if (book.Author.FirstName != null)
                {
                    // Validate the first-name element and its content.
                    validator.ValidateElement("first-name", "http://www.contoso.com/books", null);
                    validator.ValidateEndElement(null, book.Author.FirstName);
                }

                if (book.Author.LastName != null)
                {
                    // Validate the last-name element and its content.
                    validator.ValidateElement("last-name", "http://www.contoso.com/books", null);
                    validator.ValidateEndElement(null, book.Author.LastName);
                }

                // Validate the content of the author element.
                validator.ValidateEndElement(null);

                // Validate the price element and its content.
                validator.ValidateElement("price", "http://www.contoso.com/books", null);
                validator.ValidateEndElement(null, book.Price);

                // Validate the content of the book element.
                validator.ValidateEndElement(null);
            }

            // Validate the content of the bookstore element.
            validator.ValidateEndElement(null);

            // Close the XmlReader object.
            reader.Close();
        }
 void GenerateXmlSchema(String[] formats, String fileFormatType)
   {
   StreamWriter writer = File.CreateText(xmlSchemaFile + "_" + fileFormatType + ".xml");		
   XmlSchema schema;
   XmlSchemaElement element;
   XmlSchemaComplexType complexType;
   XmlSchemaSequence sequence;
   schema = new XmlSchema();
   element = new XmlSchemaElement();
   schema.Items.Add(element);
   element.Name = "Table";
   complexType = new XmlSchemaComplexType();
   element.SchemaType = complexType;
   sequence = new XmlSchemaSequence();
   complexType.Particle = sequence;
   element = new XmlSchemaElement();
   element.Name = "Number";
   element.SchemaTypeName = new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema");
   sequence.Items.Add(element);
   for(int i=0; i<formats.Length; i++){
   element = new XmlSchemaElement();
   element.Name = formats[i];
   element.SchemaTypeName = new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema");
   sequence.Items.Add(element);
   }
   schema.Compile(new ValidationEventHandler(ValidationCallbackOne));
   schema.Write(writer);
   writer.Close();
   }
Beispiel #37
0
        public void ProcessArray(XmlWriter writer, XmlSchemaElement elem, Object model, Int32 level)
        {
            Boolean WriteArrayItem(String key, IDictionary <String, Object> dict)
            {
                Boolean written = false;

                foreach (var av in dict)
                {
                    if ((key + av.Key == elem.Name) && av.Value != null)
                    {
                        var typedVal = TypedValue(elem.SchemaTypeName.Name, av.Value, elem.IsNillable);
                        if (String.IsNullOrEmpty(typedVal) && elem.IsNillable)
                        {
                            WriteNil(writer);
                        }
                        else
                        {
                            writer.WriteString(typedVal);
                        }
                        written = true;
                        break;
                    }
                }
                return(written);
            }

            if (model == null)
            {
                return;
            }
            var d = model as IDictionary <String, Object>;

            foreach (var kp in d)
            {
                if (!elem.Name.StartsWith(kp.Key))
                {
                    continue;
                }
                Boolean fullElement = kp.Key == elem.Name;
                switch (kp.Value)
                {
                case IList <Object> arr:
                    for (var i = 0; i < arr.Count; i++)
                    {
                        if (fullElement)
                        {
                            var wrapper = new ExpandoObject();
                            wrapper.Set(elem.Name, arr[i]);
                            ProcessElement(writer, elem, level + 1, wrapper, simple: false);
                        }
                        else
                        {
                            writer.WriteStartElement(elem.Name);
                            writer.WriteAttributeString("ROWNUM", (i + 1).ToString());
                            Boolean written = WriteArrayItem(kp.Key, arr[i] as IDictionary <String, Object>);
                            if (!written)
                            {
                                writer.WriteAttributeString("xsi", "nil", XmlSchema.InstanceNamespace, "true");
                            }
                            writer.WriteEndElement();
                        }
                    }
                    break;

                case IList <ExpandoObject> arrExp:
                    for (var i = 0; i < arrExp.Count; i++)
                    {
                        writer.WriteStartElement(elem.Name);
                        writer.WriteAttributeString("ROWNUM", (i + 1).ToString());
                        Boolean written = WriteArrayItem(kp.Key, arrExp[i] as IDictionary <String, Object>);
                        if (!written)
                        {
                            writer.WriteAttributeString("xsi", "nil", XmlSchema.InstanceNamespace, "true");
                        }
                        writer.WriteEndElement();
                    }
                    break;

                case ExpandoObject eo:
                    ProcessElement(writer, elem, level + 1, eo, true);
                    break;
                }
            }
        }