public void DumpSchema (XmlSchema schema) { schema.Compile (null); SortedList sl = new SortedList (); IndentLine ("**XmlSchema**"); IndentLine ("TargetNamespace: " + schema.TargetNamespace); IndentLine ("AttributeGroups:"); foreach (DictionaryEntry entry in schema.AttributeGroups) sl.Add (entry.Key.ToString (), entry.Value); foreach (DictionaryEntry entry in sl) DumpAttributeGroup ((XmlSchemaAttributeGroup) entry.Value); sl.Clear (); IndentLine ("Attributes:"); foreach (DictionaryEntry entry in schema.Attributes) sl.Add (entry.Key.ToString (), entry.Value); foreach (DictionaryEntry entry in sl) DumpAttribute ((XmlSchemaAttribute) entry.Value); sl.Clear (); IndentLine ("Elements:"); foreach (DictionaryEntry entry in schema.Elements) sl.Add (entry.Key.ToString (), entry.Value); foreach (DictionaryEntry entry in sl) DumpElement ((XmlSchemaElement) entry.Value); sl.Clear (); IndentLine ("Groups"); foreach (DictionaryEntry entry in schema.Groups) sl.Add (entry.Key.ToString (), entry.Value); foreach (DictionaryEntry entry in sl) DumpGroup ((XmlSchemaGroup) entry.Value); sl.Clear (); IndentLine ("IsCompiled: " + schema.IsCompiled); IndentLine ("Notations"); foreach (DictionaryEntry entry in schema.Notations) sl.Add (entry.Key.ToString (), entry.Value); foreach (DictionaryEntry entry in sl) DumpNotation ((XmlSchemaNotation) entry.Value); sl.Clear (); IndentLine ("SchemaTypes:"); foreach (DictionaryEntry entry in schema.Notations) sl.Add (entry.Key.ToString (), entry.Value); foreach (DictionaryEntry entry in sl) if (entry.Value is XmlSchemaSimpleType) DumpSimpleType ((XmlSchemaSimpleType) entry.Value); else DumpComplexType ((XmlSchemaComplexType) entry.Value); sl.Clear (); }
static void Validate (string xml, XmlSchema schema) { #if NET_2_0 XmlReaderSettings s = new XmlReaderSettings (); s.ValidationType = ValidationType.Schema; s.Schemas.Add (schema); XmlReader r = XmlReader.Create (new StringReader (xml), s); #else XmlTextReader xtr = new XmlTextReader (new StringReader (xml)); XmlValidatingReader r = new XmlValidatingReader (xtr); r.ValidationType = ValidationType.Schema; #endif while (!r.EOF) r.Read (); }
/// <summary> /// Instantiate a new GamingCompiler. /// </summary> public GamingCompiler() { this.schema = LoadXmlSchemaHelper(Assembly.GetExecutingAssembly(), "Microsoft.Tools.WindowsInstallerXml.Extensions.Xsd.gaming.xsd"); }
private void GenerateAttributeWildCard(XmlSchemaComplexType ct, InstanceElement elem) { char[] whitespace = new char[] { ' ', '\t', '\n', '\r' }; InstanceAttribute attr = null; XmlSchemaAttribute anyAttr = null; XmlSchemaAnyAttribute attributeWildCard = ct.AttributeWildcard; XmlSchemaObjectTable attributes = ct.AttributeUses; string namespaceList = attributeWildCard.Namespace; if (namespaceList == null) { namespaceList = "##any"; } if (attributeWildCard.ProcessContents == XmlSchemaContentProcessing.Skip || attributeWildCard.ProcessContents == XmlSchemaContentProcessing.Lax) { if (namespaceList == "##any" || namespaceList == "##targetNamespace") { attr = new InstanceAttribute(new XmlQualifiedName("any_Attr", rootTargetNamespace)); } else if (namespaceList == "##local") { attr = new InstanceAttribute(new XmlQualifiedName("any_Attr", string.Empty)); } else if (namespaceList == "##other") { attr = new InstanceAttribute(new XmlQualifiedName("any_Attr", "otherNS")); } if (attr != null) { attr.ValueGenerator = XmlValueGenerator.AnySimpleTypeGenerator; elem.AddAttribute(attr); return; } } switch (namespaceList) { case "##any": case "##targetNamespace": anyAttr = GetAttributeFromNS(rootTargetNamespace, attributes); break; case "##other": XmlSchema anySchema = GetParentSchema(attributeWildCard); anyAttr = GetAttributeFromNS(anySchema.TargetNamespace, true, attributes); break; case "##local": //Shd get local elements in some schema anyAttr = GetAttributeFromNS(string.Empty, attributes); break; default: foreach (string ns in attributeWildCard.Namespace.Split(whitespace)) { if (ns == "##local") { anyAttr = GetAttributeFromNS(string.Empty, attributes); } else if (ns == "##targetNamespace") { anyAttr = GetAttributeFromNS(rootTargetNamespace, attributes); } else { anyAttr = GetAttributeFromNS(ns, attributes); } if (anyAttr != null) //Found match { break; } } break; } if (anyAttr != null) { GenerateInstanceAttribute(anyAttr, elem); } else //Write comment in generated XML that match for wild card cd not be found. { if (elem.Comment.Length == 0) //For multiple attribute wildcards in the same element, generate comment only once { elem.Comment.Append(" Attribute Wild card could not be matched. Generated XML may not be valid. "); } } }
} //WriteExampleAttribute() // Write example particles public static void WriteExampleParticle(XmlSchemaParticle particle, XmlSchema myXmlSchema, XmlTextWriter myXmlTextWriter) { Decimal max; if (particle.MaxOccurs == -1 || particle.MaxOccurs > 10000) { max = 5; } //if else { max = particle.MaxOccurs; } //else for (int i = 0; i < max; i ++) { if (particle is XmlSchemaElement) { WriteExampleElement((XmlSchemaElement)particle, myXmlSchema, myXmlTextWriter); } //if else if (particle is XmlSchemaSequence) { foreach (XmlSchemaParticle particle1 in ((XmlSchemaSequence)particle).Items) WriteExampleParticle(particle1, myXmlSchema, myXmlTextWriter); } //else if else if (particle is XmlSchemaGroupRef) { XmlSchemaGroupRef xsgr = (XmlSchemaGroupRef)particle; XmlSchemaGroup group = (XmlSchemaGroup)myXmlSchema.Groups[xsgr.RefName]; WriteExampleParticle(group.Particle, myXmlSchema, myXmlTextWriter); } //else if else { Console.WriteLine("Not Implemented for this type: {0}", particle.ToString()); } //else } //for } //WriteExampleParticle()
internal void GetExternalSchemasList(IList extList, XmlSchema schema) { Debug.Assert(extList != null && schema != null); if (extList.Contains(schema)) { return; } extList.Add(schema); for (int i = 0; i < schema.Includes.Count; ++i) { XmlSchemaExternal ext = (XmlSchemaExternal)schema.Includes[i]; if (ext.Schema != null) { GetExternalSchemasList(extList, ext.Schema); } } }
} //Main() /// <summary> /// This method writes out the XSD object model. /// </summary> /// <param name="myXmlSchema"></param> /// <param name="myXmlTextWriter"></param> public static void WriteXSDSchema(XmlSchema myXmlSchema, XmlTextWriter myXmlTextWriter) { myXmlTextWriter.WriteStartElement("schema", XmlSchema.Namespace); myXmlTextWriter.WriteAttributeString("targetNamespace", myXmlSchema.TargetNamespace); foreach(XmlSchemaInclude include in myXmlSchema.Includes) { myXmlTextWriter.WriteStartElement("include", XmlSchema.Namespace); myXmlTextWriter.WriteAttributeString("schemaLocation", include.SchemaLocation); myXmlTextWriter.WriteEndElement(); } foreach(object item in myXmlSchema.Items) { if (item is XmlSchemaAttribute) WriteXmlSchemaAttribute((XmlSchemaAttribute)item, myXmlTextWriter); //attribute else if (item is XmlSchemaComplexType) WriteXmlSchemaComplexType((XmlSchemaComplexType)item, myXmlSchema, myXmlTextWriter); //complexType else if (item is XmlSchemaSimpleType) WriteXmlSchemaSimpleType((XmlSchemaSimpleType)item, myXmlTextWriter); //simpleType else if (item is XmlSchemaElement) WriteXmlSchemaElement((XmlSchemaElement)item, myXmlSchema, myXmlTextWriter); //element else if (item is XmlSchemaAnnotation) WriteXmlSchemaAnnotation((XmlSchemaAnnotation)item, myXmlTextWriter); //annotation else if (item is XmlSchemaAttributeGroup) WriteXmlSchemaAttributeGroup((XmlSchemaAttributeGroup)item, myXmlTextWriter); //attributeGroup else if (item is XmlSchemaNotation) WriteXmlSchemaNotation((XmlSchemaNotation)item, myXmlTextWriter); //notation else if (item is XmlSchemaGroup) WriteXmlSchemaGroup((XmlSchemaGroup)item, myXmlSchema, myXmlTextWriter, null); //group else Console.WriteLine("Not Implemented."); } //foreach myXmlTextWriter.WriteEndElement(); } //WriteXSDSchema()
} //WriteXmlSchemaAttributeGroup() //XmlSchemaGroup public static void WriteXmlSchemaGroup(XmlSchemaGroup group, XmlSchema myXmlSchema, XmlTextWriter myXmlTextWriter, string RefName) { myXmlTextWriter.WriteStartElement("group", XmlSchema.Namespace); if (RefName == null) { myXmlTextWriter.WriteAttributeString("name", XmlSchema.Namespace, group.Name); } //if else { myXmlTextWriter.WriteAttributeString("ref", XmlSchema.Namespace, RefName); } //else WriteXmlSchemaParticle(group.Particle, myXmlSchema, myXmlTextWriter); myXmlTextWriter.WriteEndElement(); } //WriteXmlSchemaGroup()
public void Bug502168() { string xsd = @"<xs:schema id='Layout' targetNamespace='foo' elementFormDefault='qualified' xmlns='foo' xmlns:xs='http://www.w3.org/2001/XMLSchema'> <xs:element name='Layout' type='Layout' /> <xs:complexType name='Layout'> <xs:group ref='AnyLayoutElement' minOccurs='0' maxOccurs='unbounded' /> </xs:complexType> <xs:group name='AnyLayoutElement'> <xs:choice> <xs:element name='Layout' type='Layout' /> <xs:element name='ImageContainer' type='ImageContainer' /> <xs:element name='VideoInstance' type='VideoInstance'/> </xs:choice> </xs:group> <xs:complexType name='ImageDummy'> </xs:complexType> <xs:complexType name='LayoutElement' abstract='true'> </xs:complexType> <xs:group name='AnyImageElement'> <xs:choice> <xs:element name='ImageDummy' type='ImageDummy' /> </xs:choice> </xs:group> <xs:complexType name='ImageContainer'> <xs:complexContent> <xs:extension base='LayoutElement'> <xs:choice minOccurs='1' maxOccurs='1'> <xs:element name='Content' type='SingleImage' minOccurs='1' maxOccurs='1' nillable='false'/> </xs:choice> </xs:extension> </xs:complexContent> </xs:complexType> <xs:complexType name='SingleImage'> <xs:group ref='AnyImageElement' minOccurs='1' maxOccurs='1'/> </xs:complexType> <xs:complexType name='VideoApplicationFile'> <xs:complexContent> <xs:extension base='VideoInstance'> <xs:attribute name='fileName' type='xs:string' use='optional'/> </xs:extension> </xs:complexContent> </xs:complexType> <xs:complexType abstract='true' name='Video'> <xs:complexContent> <xs:extension base='LayoutElement'> <xs:group ref='AnyImageElement' minOccurs='0' maxOccurs='1'/> </xs:extension> </xs:complexContent> </xs:complexType> <xs:complexType abstract='true' name='VideoInstance'> <xs:complexContent> <xs:extension base='Video'> <xs:attribute name='name' type='xs:string' use='optional'/> </xs:extension> </xs:complexContent> </xs:complexType> </xs:schema>" ; XmlDocument doc = new XmlDocument(); XmlSchema schema = XmlSchema.Read(XmlReader.Create(new StringReader(xsd)), null); doc.LoadXml(@"<Layout xmlns='foo' />"); doc.Schemas.Add(schema); doc.Validate(null); }
static XmlStrictValidation() { var reader = new StringReader(SchemaString); Schema = XmlSchema.Read(reader, null); }
private void RetrieveSerializableSchema() { if (_needSchema) { _needSchema = false; if (_getSchemaMethod != null) { // get the type info if (_schemas == null) { _schemas = new XmlSchemaSet(); } object typeInfo = _getSchemaMethod.Invoke(null, new object[] { _schemas }); _xsiType = XmlQualifiedName.Empty; if (typeInfo != null) { if (typeof(XmlSchemaType).IsAssignableFrom(_getSchemaMethod.ReturnType)) { _xsdType = (XmlSchemaType)typeInfo; // check if type is named _xsiType = _xsdType.QualifiedName; } else if (typeof(XmlQualifiedName).IsAssignableFrom(_getSchemaMethod.ReturnType)) { _xsiType = (XmlQualifiedName)typeInfo; if (_xsiType.IsEmpty) { throw new InvalidOperationException(string.Format(ResXml.XmlGetSchemaEmptyTypeName, _type.FullName, _getSchemaMethod.Name)); } } else { throw new InvalidOperationException(string.Format(ResXml.XmlGetSchemaMethodReturnType, _type.Name, _getSchemaMethod.Name, typeof(XmlSchemaProviderAttribute).Name, typeof(XmlQualifiedName).FullName)); } } else { _any = true; } // make sure that user-specified schemas are valid _schemas.ValidationEventHandler += new ValidationEventHandler(ValidationCallbackWithErrorCode); _schemas.Compile(); // at this point we verified that the information returned by the IXmlSerializable is valid // Now check to see if the type was referenced before: // UNDONE check for the duplcate types if (!_xsiType.IsEmpty) { // try to find the type in the schemas collection if (_xsiType.Namespace != XmlSchema.Namespace) { ArrayList srcSchemas = (ArrayList)_schemas.Schemas(_xsiType.Namespace); if (srcSchemas.Count == 0) { throw new InvalidOperationException(string.Format(ResXml.XmlMissingSchema, _xsiType.Namespace)); } if (srcSchemas.Count > 1) { throw new InvalidOperationException(string.Format(ResXml.XmlGetSchemaInclude, _xsiType.Namespace, _getSchemaMethod.DeclaringType.FullName, _getSchemaMethod.Name)); } XmlSchema s = (XmlSchema)srcSchemas[0]; if (s == null) { throw new InvalidOperationException(string.Format(ResXml.XmlMissingSchema, _xsiType.Namespace)); } _xsdType = (XmlSchemaType)s.SchemaTypes[_xsiType]; if (_xsdType == null) { throw new InvalidOperationException(string.Format(ResXml.XmlGetSchemaTypeMissing, _getSchemaMethod.DeclaringType.FullName, _getSchemaMethod.Name, _xsiType.Name, _xsiType.Namespace)); } _xsdType = _xsdType.Redefined != null ? _xsdType.Redefined : _xsdType; } } } else { IXmlSerializable serializable = (IXmlSerializable)Activator.CreateInstance(_type); _schema = serializable.GetSchema(); if (_schema != null) { if (_schema.Id == null || _schema.Id.Length == 0) { throw new InvalidOperationException(string.Format(ResXml.XmlSerializableNameMissing1, _type.FullName)); } } } } }
/// <summary> /// Constructor /// </summary> /// <param name="InNameToTask">Mapping of task name to information about how to construct it</param> public ScriptSchema(Dictionary <string, ScriptTask> InNameToTask) { NameToTask = InNameToTask; // Create a lookup from standard types to their qualified names Dictionary <Type, XmlQualifiedName> TypeToSchemaTypeName = new Dictionary <Type, XmlQualifiedName>(); TypeToSchemaTypeName.Add(typeof(String), GetQualifiedTypeName(ScriptSchemaStandardType.BalancedString)); TypeToSchemaTypeName.Add(typeof(Boolean), GetQualifiedTypeName(ScriptSchemaStandardType.Boolean)); TypeToSchemaTypeName.Add(typeof(Int32), GetQualifiedTypeName(ScriptSchemaStandardType.Integer)); // Create all the custom user types, and add them to the qualified name lookup List <XmlSchemaType> UserTypes = new List <XmlSchemaType>(); foreach (Type Type in NameToTask.Values.SelectMany(x => x.NameToParameter.Values).Select(x => x.ValueType)) { if (!TypeToSchemaTypeName.ContainsKey(Type)) { string Name = Type.Name + "UserType"; XmlSchemaType SchemaType = CreateUserType(Name, Type); UserTypes.Add(SchemaType); TypeToSchemaTypeName.Add(Type, new XmlQualifiedName(Name, NamespaceURI)); } } // Create all the task types Dictionary <string, XmlSchemaComplexType> TaskNameToType = new Dictionary <string, XmlSchemaComplexType>(); foreach (ScriptTask Task in NameToTask.Values) { XmlSchemaComplexType TaskType = new XmlSchemaComplexType(); TaskType.Name = Task.Name + "TaskType"; foreach (ScriptTaskParameter Parameter in Task.NameToParameter.Values) { XmlQualifiedName SchemaTypeName = GetQualifiedTypeName(Parameter.ValidationType); if (SchemaTypeName == null) { SchemaTypeName = TypeToSchemaTypeName[Parameter.ValueType]; } TaskType.Attributes.Add(CreateSchemaAttribute(Parameter.Name, SchemaTypeName, Parameter.bOptional? XmlSchemaUse.Optional : XmlSchemaUse.Required)); } TaskType.Attributes.Add(CreateSchemaAttribute("If", ScriptSchemaStandardType.BalancedString, XmlSchemaUse.Optional)); TaskNameToType.Add(Task.Name, TaskType); } // Create the schema object XmlSchema NewSchema = new XmlSchema(); NewSchema.TargetNamespace = NamespaceURI; NewSchema.ElementFormDefault = XmlSchemaForm.Qualified; NewSchema.Items.Add(CreateSchemaElement(RootElementName, ScriptSchemaStandardType.Graph)); NewSchema.Items.Add(CreateGraphType()); NewSchema.Items.Add(CreateTriggerType()); NewSchema.Items.Add(CreateTriggerBodyType()); NewSchema.Items.Add(CreateAgentType()); NewSchema.Items.Add(CreateAgentBodyType()); NewSchema.Items.Add(CreateNodeType()); NewSchema.Items.Add(CreateNodeBodyType(TaskNameToType)); NewSchema.Items.Add(CreateAggregateType()); NewSchema.Items.Add(CreateReportType()); NewSchema.Items.Add(CreateBadgeType()); NewSchema.Items.Add(CreateNotifyType()); NewSchema.Items.Add(CreateIncludeType()); NewSchema.Items.Add(CreateOptionType()); NewSchema.Items.Add(CreateEnvVarType()); NewSchema.Items.Add(CreatePropertyType()); NewSchema.Items.Add(CreateMacroType()); NewSchema.Items.Add(CreateExpandType()); NewSchema.Items.Add(CreateDiagnosticType(ScriptSchemaStandardType.Trace)); NewSchema.Items.Add(CreateDiagnosticType(ScriptSchemaStandardType.Warning)); NewSchema.Items.Add(CreateDiagnosticType(ScriptSchemaStandardType.Error)); NewSchema.Items.Add(CreateSimpleTypeFromRegex(GetTypeName(ScriptSchemaStandardType.Name), "(" + NamePattern + "|" + StringWithPropertiesPattern + ")")); NewSchema.Items.Add(CreateSimpleTypeFromRegex(GetTypeName(ScriptSchemaStandardType.NameList), "(" + NameListPattern + "|" + StringWithPropertiesPattern + ")")); NewSchema.Items.Add(CreateSimpleTypeFromRegex(GetTypeName(ScriptSchemaStandardType.Tag), "(" + TagPattern + "|" + StringWithPropertiesPattern + ")")); NewSchema.Items.Add(CreateSimpleTypeFromRegex(GetTypeName(ScriptSchemaStandardType.TagList), "(" + TagListPattern + "|" + StringWithPropertiesPattern + ")")); NewSchema.Items.Add(CreateSimpleTypeFromRegex(GetTypeName(ScriptSchemaStandardType.NameOrTag), "(" + NameOrTagPattern + "|" + StringWithPropertiesPattern + ")")); NewSchema.Items.Add(CreateSimpleTypeFromRegex(GetTypeName(ScriptSchemaStandardType.NameOrTagList), "(" + NameOrTagListPattern + "|" + StringWithPropertiesPattern + ")")); NewSchema.Items.Add(CreateSimpleTypeFromRegex(GetTypeName(ScriptSchemaStandardType.QualifiedName), "(" + QualifiedNamePattern + "|" + StringWithPropertiesPattern + ")")); NewSchema.Items.Add(CreateSimpleTypeFromRegex(GetTypeName(ScriptSchemaStandardType.BalancedString), BalancedStringPattern)); NewSchema.Items.Add(CreateSimpleTypeFromRegex(GetTypeName(ScriptSchemaStandardType.Boolean), "(" + "true" + "|" + "false" + "|" + StringWithPropertiesPattern + ")")); NewSchema.Items.Add(CreateSimpleTypeFromRegex(GetTypeName(ScriptSchemaStandardType.Integer), "(" + "(-?[1-9][0-9]*|0)" + "|" + StringWithPropertiesPattern + ")")); foreach (XmlSchemaComplexType Type in TaskNameToType.Values) { NewSchema.Items.Add(Type); } foreach (XmlSchemaSimpleType Type in UserTypes) { NewSchema.Items.Add(Type); } // Now that we've finished, compile it and store it to the class XmlSchemaSet NewSchemaSet = new XmlSchemaSet(); NewSchemaSet.Add(NewSchema); NewSchemaSet.Compile(); foreach (XmlSchema NewCompiledSchema in NewSchemaSet.Schemas()) { CompiledSchema = NewCompiledSchema; } }
private XmlSchema LoadSchema(string schemaPath) { var xmlReader = XmlReader.Create(schemaPath); return(XmlSchema.Read(xmlReader, new ValidationEventHandler(SchemaValidationEventHandler))); }
public XmlSampleGenerator(string url, XmlQualifiedName rootElem) : this(XmlSchema.Read(new XmlTextReader(url), new ValidationEventHandler(ValidationCallBack)), rootElem) { }
private void GenerateAny(XmlSchemaAny any, InstanceGroup grp) { InstanceElement parentElem = grp as InstanceElement; char[] whitespace = new char[] { ' ', '\t', '\n', '\r' }; InstanceElement elem = null; XmlSchemaElement anyElem = null; string namespaceList = any.Namespace; if (namespaceList == null) //no namespace defaults to "##any" { namespaceList = "##any"; } if (any.ProcessContents == XmlSchemaContentProcessing.Skip || any.ProcessContents == XmlSchemaContentProcessing.Lax) { if (namespaceList == "##any" || namespaceList == "##targetNamespace") { elem = new InstanceElement(new XmlQualifiedName("any_element", rootTargetNamespace)); } else if (namespaceList == "##local") { elem = new InstanceElement(new XmlQualifiedName("any_element", string.Empty)); } else if (namespaceList == "##other") { elem = new InstanceElement(new XmlQualifiedName("any_element", "otherNS")); } if (elem != null) { elem.ValueGenerator = XmlValueGenerator.AnyGenerator; elem.Occurs = any.MaxOccurs >= maxThreshold ? maxThreshold : any.MaxOccurs; elem.Occurs = any.MinOccurs > elem.Occurs ? any.MinOccurs : elem.Occurs; grp.AddChild(elem); return; } } //ProcessContents = strict || namespaceList is actually a list of namespaces switch (namespaceList) { case "##any": case "##targetNamespace": anyElem = GetElementFromNS(rootTargetNamespace); break; case "##other": XmlSchema anySchema = GetParentSchema(any); anyElem = GetElementFromNS(anySchema.TargetNamespace, true); break; case "##local": //Shd get local elements in some schema anyElem = GetElementFromNS(string.Empty); break; default: foreach (string ns in namespaceList.Split(whitespace)) { if (ns == "##targetNamespace") { anyElem = GetElementFromNS(rootTargetNamespace); } else if (ns == "##local") { anyElem = GetElementFromNS(string.Empty); } else { anyElem = GetElementFromNS(ns); } if (anyElem != null) //found a match { break; } } break; } if (anyElem != null && GenerateElement(anyElem, false, grp, any)) { return; } else //Write comment in generated XML that match for wild card cd not be found. { if (parentElem == null) { parentElem = GetParentInstanceElement(grp); } if (parentElem.Comment.Length == 0) //For multiple wildcards in the same element, generate comment only once { parentElem.Comment.Append(" Element Wild card could not be matched. Generated XML may not be valid. "); } } }
public XmlSchema Add(XmlSchema schema) { }
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); }
public bool Contains(XmlSchema schema) { }
private void SetElementType(XmlSchemaElement element, DataContract dataContract, XmlSchema schema) { XmlDataContract xmlDataContract = dataContract as XmlDataContract; if (xmlDataContract != null && xmlDataContract.IsAnonymous) { element.SchemaType = xmlDataContract.XsdType; } else { element.SchemaTypeName = dataContract.StableName; if (element.SchemaTypeName.Namespace.Equals(Globals.SerializationNamespace)) { schema.Namespaces.Add(Globals.SerPrefixForSchema, Globals.SerializationNamespace); } SchemaHelper.AddSchemaImport(dataContract.StableName.Namespace, schema); } }
// Methods public void AddSchema(XmlSchema schema) { }
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); } }
} //WriteXmlSchemaSimpleType() //XmlSchemaParticle public static void WriteXmlSchemaParticle(XmlSchemaParticle particle, XmlSchema myXmlSchema, XmlTextWriter myXmlTextWriter) { if (particle is XmlSchemaElement) { WriteXmlSchemaElement((XmlSchemaElement)particle, myXmlSchema, myXmlTextWriter); } //if else if (particle is XmlSchemaSequence) { myXmlTextWriter.WriteStartElement("sequence", XmlSchema.Namespace); foreach(XmlSchemaParticle particle1 in ((XmlSchemaSequence)particle).Items) WriteXmlSchemaParticle(particle1, myXmlSchema, myXmlTextWriter); myXmlTextWriter.WriteEndElement(); } //else if else if (particle is XmlSchemaGroupRef) { XmlSchemaGroupRef xsgr = (XmlSchemaGroupRef)particle; XmlSchemaGroup group = (XmlSchemaGroup)myXmlSchema.Groups[xsgr.RefName]; WriteXmlSchemaGroup(group, myXmlSchema, myXmlTextWriter, xsgr.RefName.Name); } //else if else { Console.WriteLine("Not Implemented for this type: {0}", particle.ToString()); } //else } //WriteXmlSchemaParticle()
private XmlSchemaComplexContentExtension CreateTypeContent(XmlSchemaComplexType type, XmlQualifiedName baseTypeName, XmlSchema schema) { SchemaHelper.AddSchemaImport(baseTypeName.Namespace, schema); XmlSchemaComplexContentExtension extension = new XmlSchemaComplexContentExtension(); extension.BaseTypeName = baseTypeName; type.ContentModel = new XmlSchemaComplexContent(); type.ContentModel.Content = extension; return(extension); }
} //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()
private XmlSchemaAnnotation GetSchemaAnnotation(XmlQualifiedName annotationQualifiedName, string innerText, XmlSchema schema) { XmlSchemaAnnotation annotation = new XmlSchemaAnnotation(); XmlSchemaAppInfo appInfo = new XmlSchemaAppInfo(); XmlElement annotationElement = GetAnnotationMarkup(annotationQualifiedName, innerText, schema); appInfo.Markup = new XmlNode[1] { annotationElement }; annotation.Items.Add(appInfo); return(annotation); }
internal new XmlSchema Clone() { XmlSchema that = new XmlSchema(); that.attributeFormDefault = this.attributeFormDefault; that.elementFormDefault = this.elementFormDefault; that.blockDefault = this.blockDefault; that.finalDefault = this.finalDefault; that.targetNs = this.targetNs; that.version = this.version; that.includes = this.includes; that.Namespaces = this.Namespaces; that.items = this.items; that.BaseUri = this.BaseUri; SchemaCollectionCompiler.Cleanup(that); return that; }
public XmlSchema Remove(XmlSchema schema) { }
public static void Add(this XmlSchema that, XmlSchemaElement el) { that.Items.Add(el); }
public XmlSchema Reprocess(XmlSchema schema) { }
private XmlElement GetAnnotationMarkup(XmlQualifiedName annotationQualifiedName, string innerText, XmlSchema schema) { XmlElement annotationElement = XmlDoc.CreateElement(annotationQualifiedName.Name, annotationQualifiedName.Namespace); SchemaHelper.AddSchemaImport(annotationQualifiedName.Namespace, schema); annotationElement.InnerText = innerText; return(annotationElement); }
public static void Add(this XmlSchema that, XmlSchemaAttribute at) { that.Items.Add(at); }
public bool RemoveRecursive(XmlSchema schemaToRemove) { }
/// <summary> /// Returns the TypeManager for the type t /// </summary> /// <param name="t">The type of the TypeManager</param> /// <returns>The TypeManager of type t if it is contained in the Dictionary, null otherwise</returns> public static Field CreateField(XmlSchemaElement schema) { Field element = null; try { XmlSchemaType type = schema.ElementSchemaType; if (type == null) { type = schema.SchemaType; } if (type == null) { type = Types.SchemaTypes[schema.SchemaTypeName] as XmlSchemaType; } if (type.Name != null) { element = CreateField(type.Name, schema.Name, null); } else { if (type is XmlSchemaComplexType && (type as XmlSchemaComplexType).Particle is XmlSchemaChoice) { XmlSchema onTheFlySchema = new XmlSchema(); onTheFlySchema.Items.Add(schema); element = CreateField("ChoiceBox", schema.Name, onTheFlySchema); } if (type is XmlSchemaComplexType && (type as XmlSchemaComplexType).Particle is XmlSchemaSequence) { if (schema.MinOccurs <= schema.MaxOccurs) { XmlSchema onTheFlySchema = new XmlSchema(); String onTheFlyName = "Sequence" + new Random().Next().ToString(); XmlSchemaElement baseElement = new XmlSchemaElement(); XmlSchemaComplexType baseType = new XmlSchemaComplexType(); XmlSchemaSequence baseSequence = new XmlSchemaSequence(); baseSequence.Items.Add(schema); baseType.Particle = baseSequence; baseElement.SchemaType = baseType; onTheFlySchema.Items.Add(baseElement); baseElement.Name = onTheFlyName; element = CreateField("SequenceBox", onTheFlyName, onTheFlySchema); } } } } catch (ArgumentException) { return(null); } return(element); }
public void CopyTo(XmlSchema[] schemas, int index) { }
public void v10() { XmlCachedSchemaSetResolver resolver = new XmlCachedSchemaSetResolver(); XmlTextReader r = new XmlTextReader(Path.Combine(TestData._Root, @"RedefineEmployee.xsd")); XmlSchema s = XmlSchema.Read(r, null); resolver.Add(new Uri(s.SourceUri), s); XmlTextReader r2 = new XmlTextReader(Path.Combine(TestData._Root, @"BaseEmployee2.xsd")); XmlSchema s2 = XmlSchema.Read(r2, null); resolver.Add(new Uri(s2.SourceUri), s2); XmlSchemaSet set = new XmlSchemaSet(); set.ValidationEventHandler += new ValidationEventHandler(callback); set.XmlResolver = resolver; set.Add(s2); Assert.Equal(set.Count, 1); Assert.Equal(set.Contains(s2), true); Assert.Equal(set.IsCompiled, false); set.Add(s); Assert.Equal(set.Count, 2); Assert.Equal(set.Contains(s), true); Assert.Equal(set.IsCompiled, false); set.Compile(); Assert.Equal(set.Count, 2); Assert.Equal(set.Contains(s2), true); Assert.Equal(set.Contains(s), true); Assert.Equal(set.IsCompiled, true); XmlTextReader r3 = new XmlTextReader(Path.Combine(TestData._Root, @"BaseEmployee2.xsd")); XmlSchema s3 = XmlSchema.Read(r3, null); resolver.Add(new Uri(s3.SourceUri), s3); //Clear includes in S foreach (XmlSchemaExternal ext in s.Includes) { ext.Schema = null; } XmlSchemaSet set2 = new XmlSchemaSet(); set2.ValidationEventHandler += new ValidationEventHandler(callback); set2.XmlResolver = resolver; set2.Add(s3); Assert.Equal(set2.Count, 1); Assert.Equal(set2.Contains(s2), false); Assert.Equal(set2.Contains(s), false); Assert.Equal(set2.Contains(s3), true); Assert.Equal(set2.IsCompiled, false); set2.Add(s); Assert.Equal(set2.Count, 2); Assert.Equal(set2.Contains(s2), false); Assert.Equal(set2.Contains(s), true); Assert.Equal(set2.Contains(s3), true); Assert.Equal(set2.IsCompiled, false); set2.Compile(); Assert.Equal(set2.Count, 2); Assert.Equal(set2.Contains(s2), false); Assert.Equal(set2.Contains(s), true); Assert.Equal(set2.Contains(s3), true); Assert.Equal(set2.IsCompiled, true); Assert.Equal(errorCount, 0); }
public XmlSchema Add(XmlSchema schema, System.Xml.XmlResolver resolver) { }
public void v11() { XmlCachedSchemaSetResolver resolver = new XmlCachedSchemaSetResolver(); XmlTextReader r = new XmlTextReader(Path.Combine(TestData._Root, @"RedefineEmployee.xsd")); XmlSchema s = XmlSchema.Read(r, null); resolver.Add(new Uri(s.SourceUri), s); XmlTextReader r2 = new XmlTextReader(Path.Combine(TestData._Root, @"BaseEmployee2.xsd")); XmlSchema s2 = XmlSchema.Read(r2, null); resolver.Add(new Uri(s2.SourceUri), s2); XmlSchemaSet set = new XmlSchemaSet(); set.XmlResolver = resolver; set.Add(s2); Assert.Equal(set.Count, 1); Assert.Equal(set.Contains(s2), true); Assert.Equal(set.IsCompiled, false); set.Add(s); Assert.Equal(set.Count, 2); Assert.Equal(set.Contains(s), true); Assert.Equal(set.IsCompiled, false); set.Compile(); Assert.Equal(set.Count, 2); Assert.Equal(set.Contains(s2), true); Assert.Equal(set.Contains(s), true); Assert.Equal(set.IsCompiled, true); XmlReaderSettings settings = new XmlReaderSettings(); settings.ValidationType = ValidationType.Schema; settings.Schemas = set; using (XmlReader reader = XmlReader.Create(Path.Combine(TestData._Root, "EmployeesDefaultPrefix.xml"), settings)) { while (reader.Read()) { ; } } XmlTextReader r3 = new XmlTextReader(Path.Combine(TestData._Root, @"BaseEmployee2.xsd")); XmlSchema s3 = XmlSchema.Read(r3, null); resolver.Add(new Uri(s3.SourceUri), s3); XmlSchemaSet set2 = new XmlSchemaSet(); set2.XmlResolver = resolver; set2.Add(s3); Assert.Equal(set2.Count, 1); Assert.Equal(set2.Contains(s2), false); Assert.Equal(set2.Contains(s), false); Assert.Equal(set2.Contains(s3), true); Assert.Equal(set2.IsCompiled, false); foreach (XmlSchemaRedefine redefine in s.Includes) { redefine.Schema = null; } set2.Add(s); Assert.Equal(set2.Count, 2); Assert.Equal(set2.Contains(s2), false); Assert.Equal(set2.Contains(s), true); Assert.Equal(set2.Contains(s3), true); Assert.Equal(set2.IsCompiled, false); set2.Compile(); Assert.Equal(set2.Count, 2); Assert.Equal(set2.Contains(s2), false); Assert.Equal(set2.Contains(s), true); Assert.Equal(set2.Contains(s3), true); Assert.Equal(set2.IsCompiled, true); settings.Schemas = set2; using (XmlReader reader = XmlReader.Create(Path.Combine(TestData._Root, "EmployeesDefaultPrefix.xml"), settings)) { while (reader.Read()) { ; } } Assert.Equal(errorCount, 0); }
public void CopyTo(XmlSchema[] array, int index) { }
public void Add(Uri uri, XmlSchema schema) { schemas[uri] = 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 XmlSchemaComplexType GetSchema(XmlSchemaSet schemas) { string XmlSchemaNamespace = "http://www.w3.org/2001/XMLSchema"; var schema = schemas.Schemas(NAMESPACE).OfType <XmlSchema>().FirstOrDefault(); if (schema == null) { schema = new XmlSchema { TargetNamespace = NAMESPACE, ElementFormDefault = XmlSchemaForm.Qualified }; schemas.Add(schema); } var seq = new XmlSchemaSequence(); seq.Items.Add(new XmlSchemaElement { Name = "InfoKey", SchemaTypeName = new XmlQualifiedName("AdditionalErrorInfoType", NAMESPACE) }); seq.Items.Add(new XmlSchemaElement { Name = "InfoValue", SchemaTypeName = new XmlQualifiedName("string", XmlSchemaNamespace) }); var infoItemElement = new XmlSchemaElement { Name = "InfoItem", MinOccurs = 0, MaxOccursString = "unbounded", SchemaType = new XmlSchemaComplexType { Particle = seq } }; seq = new XmlSchemaSequence(); seq.Items.Add(infoItemElement); var additionalInfoType = new XmlSchemaComplexType { Name = "AdditionalInfo", Particle = seq }; var doc = new XmlDocument(); var isDict = doc.CreateElement("IsDictionary", "http://schemas.microsoft.com/2003/10/Serialization/"); isDict.InnerText = "true"; var annotation = new XmlSchemaAnnotation(); annotation.Items.Add(new XmlSchemaAppInfo() { Markup = new[] { isDict } }); additionalInfoType.Annotation = annotation; schema.Items.Add(additionalInfoType); schema.Items.Add(new XmlSchemaElement { Name = "AdditionalInfo", IsNillable = true, SchemaTypeName = new XmlQualifiedName("AdditionalInfo", NAMESPACE) }); var exporter = new XsdDataContractExporter(); exporter.Export(typeof(AdditionalErrorInfoType)); foreach (XmlSchema sch in exporter.Schemas.Schemas(NAMESPACE)) { foreach (var item in sch.Items) { schema.Items.Add(item); } } return(additionalInfoType); }
public static void Main() { XmlSchema schema = new XmlSchema(); // <xs:simpleType name="RatingType"> XmlSchemaSimpleType RatingType = new XmlSchemaSimpleType(); RatingType.Name = "RatingType"; // <xs:restriction base="xs:number"> XmlSchemaSimpleTypeRestriction restriction = new XmlSchemaSimpleTypeRestriction(); restriction.BaseTypeName = new XmlQualifiedName("decimal", "http://www.w3.org/2001/XMLSchema"); // <xs:totalDigits value="2"/> XmlSchemaTotalDigitsFacet totalDigits = new XmlSchemaTotalDigitsFacet(); totalDigits.Value = "2"; restriction.Facets.Add(totalDigits); // <xs:fractionDigits value="1"/> XmlSchemaFractionDigitsFacet fractionDigits = new XmlSchemaFractionDigitsFacet(); fractionDigits.Value = "1"; restriction.Facets.Add(fractionDigits); RatingType.Content = restriction; schema.Items.Add(RatingType); // <xs:element name="movie"> XmlSchemaElement element = new XmlSchemaElement(); element.Name = "movie"; // <xs:complexType> XmlSchemaComplexType complexType = new XmlSchemaComplexType(); // <xs:attribute name="rating" type="RatingType"/> XmlSchemaAttribute ratingAttribute = new XmlSchemaAttribute(); ratingAttribute.Name = "rating"; ratingAttribute.SchemaTypeName = new XmlQualifiedName("RatingType", ""); complexType.Attributes.Add(ratingAttribute); element.SchemaType = complexType; schema.Items.Add(element); 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); }
/// <summary> /// Loads the schema for search Engines into an XmlSchema object. /// </summary> private void LoadSearchConfigSchema() { using (Stream stream = Resource.GetStream("Resources.SearchEnginesConfig.xsd")) { searchConfigSchema = XmlSchema.Read(stream, null); } }
} //WriteXmlSchemaAttribute() /// <summary> /// /// </summary> /// <param name="complexType"></param> /// <param name="myXmlSchema"></param> /// <param name="myXmlTextWriter"></param> public static void WriteXmlSchemaComplexType(XmlSchemaComplexType complexType, XmlSchema myXmlSchema, XmlTextWriter myXmlTextWriter) { myXmlTextWriter.WriteStartElement("complexType", XmlSchema.Namespace); if (complexType.Name != null) { myXmlTextWriter.WriteAttributeString("name", complexType.Name); } //if if (complexType.ContentModel != null) { Console.WriteLine("Not Implemented for this ContentModel."); } //if else { if (complexType.Particle != null) WriteXmlSchemaParticle(complexType.Particle, myXmlSchema, myXmlTextWriter); foreach(object o in complexType.Attributes) { if (o is XmlSchemaAttribute) WriteXmlSchemaAttribute((XmlSchemaAttribute)o, myXmlTextWriter); } //foreach } //else myXmlTextWriter.WriteEndElement(); } //WriteXmlSchemaComplexType()
/// <summary> /// Initiate code generation process /// </summary> /// <param name="generatorParams">Generator parameters</param> /// <returns></returns> internal static Result <CodeNamespace> Process(GeneratorParams generatorParams) { var ns = new CodeNamespace(); XmlReader reader = null; try { #region Set generation context GeneratorContext.GeneratorParams = generatorParams; #endregion #region Get XmlTypeMapping XmlSchema xsd; var schemas = new XmlSchemas(); reader = XmlReader.Create(generatorParams.InputFilePath); xsd = XmlSchema.Read(reader, new ValidationEventHandler(Validate)); var schemaSet = new XmlSchemaSet(); schemaSet.Add(xsd); schemaSet.Compile(); foreach (XmlSchema schema in schemaSet.Schemas()) { schemas.Add(schema); } var exporter = new XmlCodeExporter(ns); var generationOptions = CodeGenerationOptions.None; if (generatorParams.Serialization.GenerateOrderXmlAttributes) { generationOptions = CodeGenerationOptions.GenerateOrder; } var importer = new XmlSchemaImporter(schemas, generationOptions, new ImportContext(new CodeIdentifiers(), false)); foreach (XmlSchemaElement element in xsd.Elements.Values) { var mapping = importer.ImportTypeMapping(element.QualifiedName); exporter.ExportTypeMapping(mapping); } //Fixes/handles http://xsd2code.codeplex.com/WorkItem/View.aspx?WorkItemId=6941 foreach (XmlSchemaType type in xsd.Items.OfType <XmlSchemaType>()) { var mapping = importer.ImportSchemaType(type.QualifiedName); exporter.ExportTypeMapping(mapping); } #endregion #region Execute extensions var getExtensionResult = GeneratorFactory.GetCodeExtension(generatorParams); if (!getExtensionResult.Success) { return(new Result <CodeNamespace>(ns, false, getExtensionResult.Messages)); } var ext = getExtensionResult.Entity; ext.Process(ns, xsd); #endregion Execute extensions return(new Result <CodeNamespace>(ns, true)); } catch (Exception e) { return(new Result <CodeNamespace>(ns, false, e.Message, MessageType.Error)); } finally { if (reader != null) { reader.Close(); } } }
} //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()
public void Validate() { logger.Log($"Launch {XmlFile} validation ... "); XmlReaderSettings settings = new XmlReaderSettings { //Message:Impossible de résoudre l'attribut 'schemaLocation'. //Error while XML validation: Pour des raisons de sécurité, DTD interdite dans ce document XML. Pour activer le traitement DTD, définissez sur Parse la propriété DtdProcessing sur XmlReaderSettings et transmettez les paramètres à la méthode XmlReader.Create. * *** DtdProcessing = DtdProcessing.Parse, MaxCharactersFromEntities = 1024, ValidationType = ValidationType.Schema }; try { settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessInlineSchema; settings.ValidationFlags |= XmlSchemaValidationFlags.AllowXmlAttributes; // settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessIdentityConstraints; // settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessSchemaLocation; if (ShowWarnings) { settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings; } foreach (var xsd_file in XsdFiles) { if (File.Exists(xsd_file)) { settings.Schemas.Add(null, new XmlTextReader(xsd_file)); } else { logger.Log($"{xsd_file} doesn't exist"); } } settings.Schemas.Compile(); settings.ValidationEventHandler += new ValidationEventHandler(ValidationHandler); using (XmlTextReader xmltextReader = new XmlTextReader(this.XmlFile) { DtdProcessing = DtdProcessing.Parse }) { using (XmlReader reader = XmlReader.Create(xmltextReader, settings)) { reader.MoveToContent(); while (reader.Read()) { } } } logger.Log($"{XmlFile} Validation finished successfully"); } catch (Exception e) { logger.Log($"Error while XML validation: {e.Message}", true); logger.Log($"{XmlFile} Validation FAILED"); } finally { ArrayList a = new ArrayList(); foreach (var item in settings.Schemas.Schemas()) { XmlSchema xmlSchema = item as XmlSchema; if (xmlSchema != null) { a.Add(xmlSchema); } } for (int i = 0; i < a.Count; i++) { settings.Schemas.Remove(a[i] as XmlSchema); } settings.Schemas = null; settings.CloseInput = true; } }
} //WriteXmlSchemaNotation() // Write out the example of the XSD usage public static void WriteExample(XmlSchema myXmlSchema, XmlTextWriter myXmlTextWriter) { foreach(XmlSchemaElement element in myXmlSchema.Elements.Values) { WriteExampleElement(element, myXmlSchema, myXmlTextWriter); } //foreach } //WriteExample()
/// <summary> /// Checks validity of a document or document fragment against the current schema /// </summary> public static void ValidatesAgainstSchema(Object obj, string expectedTypeInSkylineSchema = null) { var sb = new StringBuilder(); using (var sw = new StringWriter(sb)) { using (var writer = new XmlTextWriter(sw)) { writer.Formatting = Formatting.Indented; try { var ser = new XmlSerializer(obj.GetType()); ser.Serialize(writer, obj); var xmlText = sb.ToString(); var assembly = Assembly.GetAssembly(typeof(AssertEx)); var xsdName = typeof(AssertEx).Namespace + String.Format(CultureInfo.InvariantCulture, ".Schemas.Skyline_{0}.xsd", SrmDocument.FORMAT_VERSION); var schemaStream = assembly.GetManifestResourceStream(xsdName); Assert.IsNotNull(schemaStream); var schemaText = (new StreamReader(schemaStream)).ReadToEnd(); string targetXML = null; if (!(obj is SrmDocument)) { // XSD validation takes place from the root, so make the object's type a root element for test purposes. // Inspired by http://stackoverflow.com/questions/715626/validating-xml-nodes-not-the-entire-document var elementName = xmlText.Split('<')[2].Split(' ')[0]; var xd = new XmlDocument(); xd.Load(new MemoryStream(Encoding.UTF8.GetBytes(schemaText))); var nodes = xd.GetElementsByTagName("xs:element"); for (var i = 0; i < nodes.Count; i++) { var xmlAttributeCollection = nodes[i].Attributes; if (xmlAttributeCollection != null && elementName.Equals(xmlAttributeCollection.GetNamedItem("name").Value) && (expectedTypeInSkylineSchema == null || expectedTypeInSkylineSchema.Equals(xmlAttributeCollection.GetNamedItem("type").Value))) { // Insert this XML as a root element at the end of the schema xmlAttributeCollection.RemoveNamedItem("minOccurs"); // Useful only in the full sequence context xmlAttributeCollection.RemoveNamedItem("maxOccurs"); var xml = nodes[i].OuterXml; if (!xml.Equals(targetXML)) { // Don't enter a redundant definition targetXML = xml; var lines = schemaText.Split('\n'); schemaText = String.Join("\n", lines.Take(lines.Count() - 2)); schemaText += xml; schemaText += lines[lines.Count() - 2]; schemaText += lines[lines.Count() - 1]; } } } } using (var schemaReader = new XmlTextReader(new MemoryStream(Encoding.UTF8.GetBytes(schemaText)))) { var schema = XmlSchema.Read(schemaReader, ValidationCallBack); var readerSettings = new XmlReaderSettings { ValidationType = ValidationType.Schema }; readerSettings.ValidationFlags |= XmlSchemaValidationFlags.ProcessInlineSchema; readerSettings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings; readerSettings.ValidationEventHandler += ValidationCallBack; readerSettings.Schemas.Add(schema); using (var reader = XmlReader.Create(new StringReader(xmlText), readerSettings)) { try { while (reader.Read()) { } reader.Close(); } catch (Exception e) { Assert.Fail(e.Message + " XML text:\r\n" + xmlText); } } } } catch (Exception e) { Assert.Fail(e.ToString()); } } } }
} //WriteExampleElement() // Write some example attributes public static void WriteExampleAttributes(XmlSchemaObjectCollection attributes, XmlSchema myXmlSchema, XmlTextWriter myXmlTextWriter) { foreach(object o in attributes) { if (o is XmlSchemaAttribute) { WriteExampleAttribute((XmlSchemaAttribute)o, myXmlTextWriter); } //if else { XmlSchemaAttributeGroupRef xsagr = (XmlSchemaAttributeGroupRef)o; XmlSchemaAttributeGroup group = (XmlSchemaAttributeGroup)myXmlSchema.AttributeGroups[xsagr.RefName]; WriteExampleAttributes(group.Attributes, myXmlSchema, myXmlTextWriter); } //else } //foreach } //WriteExampleAttributes()
public static XmlSchemaComplexType GetTypedTableSchema(XmlSchemaSet xs) { XmlSchemaComplexType type2 = new XmlSchemaComplexType(); XmlSchemaSequence sequence = new XmlSchemaSequence(); dsipp dsipp = new dsipp(); XmlSchemaAny item = new XmlSchemaAny { Namespace = "http://www.w3.org/2001/XMLSchema" }; decimal num = new decimal(0); item.MinOccurs = num; item.MaxOccurs = 79228162514264337593543950335M; item.ProcessContents = XmlSchemaContentProcessing.Lax; sequence.Items.Add(item); XmlSchemaAny any2 = new XmlSchemaAny { Namespace = "urn:schemas-microsoft-com:xml-diffgram-v1" }; num = new decimal(1); any2.MinOccurs = num; any2.ProcessContents = XmlSchemaContentProcessing.Lax; sequence.Items.Add(any2); XmlSchemaAttribute attribute = new XmlSchemaAttribute { Name = "namespace", FixedValue = dsipp.Namespace }; type2.Attributes.Add(attribute); XmlSchemaAttribute attribute2 = new XmlSchemaAttribute { Name = "tableTypeName", FixedValue = "porezDataTable" }; type2.Attributes.Add(attribute2); type2.Particle = sequence; XmlSchema schemaSerializable = dsipp.GetSchemaSerializable(); if (xs.Contains(schemaSerializable.TargetNamespace)) { MemoryStream stream = new MemoryStream(); MemoryStream stream2 = new MemoryStream(); try { XmlSchema current = null; schemaSerializable.Write(stream); IEnumerator enumerator = xs.Schemas(schemaSerializable.TargetNamespace).GetEnumerator(); while (enumerator.MoveNext()) { current = (XmlSchema)enumerator.Current; stream2.SetLength(0L); current.Write(stream2); if (stream.Length == stream2.Length) { stream.Position = 0L; stream2.Position = 0L; while ((stream.Position != stream.Length) && (stream.ReadByte() == stream2.ReadByte())) { } if (stream.Position == stream.Length) { return(type2); } } } } finally { if (stream != null) { stream.Close(); } if (stream2 != null) { stream2.Close(); } } } xs.Add(schemaSerializable); return(type2); }
internal new XmlSchema Clone() { XmlSchema that = new XmlSchema(); that._attributeFormDefault = _attributeFormDefault; that._elementFormDefault = _elementFormDefault; that._blockDefault = _blockDefault; that._finalDefault = _finalDefault; that._targetNs = _targetNs; that._version = _version; that._includes = _includes; that.Namespaces = this.Namespaces; that._items = _items; that.BaseUri = this.BaseUri; SchemaCollectionCompiler.Cleanup(that); return that; }
public void Bug501763() { string xsd1 = @" <xs:schema id='foo1' targetNamespace='foo1' elementFormDefault='qualified' xmlns='foo1' xmlns:xs='http://www.w3.org/2001/XMLSchema' xmlns:f2='foo2'> <xs:import namespace='foo2' /> <xs:element name='Foo1Element' type='f2:Foo2ExtendedType'/> </xs:schema>" ; string xsd2 = @" <xs:schema id='foo2' targetNamespace='foo2' elementFormDefault='qualified' xmlns='foo2' xmlns:xs='http://www.w3.org/2001/XMLSchema' > <xs:element name='Foo2Element' type='Foo2Type' /> <xs:complexType name='Foo2Type'> <xs:attribute name='foo2Attr' type='xs:string' use='required'/> </xs:complexType> <xs:complexType name='Foo2ExtendedType'> <xs:complexContent> <xs:extension base='Foo2Type'> <xs:attribute name='foo2ExtAttr' type='xs:string' use='required'/> </xs:extension> </xs:complexContent> </xs:complexType> </xs:schema>" ; XmlDocument doc = new XmlDocument(); XmlSchema schema1 = XmlSchema.Read(XmlReader.Create(new StringReader(xsd1)), null); XmlSchema schema2 = XmlSchema.Read(XmlReader.Create(new StringReader(xsd2)), null); doc.LoadXml(@" <Foo2Element foo2Attr='dummyvalue1' xmlns='foo2' />" ); doc.Schemas.Add(schema2); doc.Validate(null); doc = new XmlDocument(); doc.LoadXml(@" <Foo1Element foo2Attr='dummyvalue1' foo2ExtAttr='dummyvalue2' xmlns='foo1' />" ); doc.Schemas.Add(schema2); doc.Schemas.Add(schema1); doc.Validate(null); }
internal XmlSchema DeepClone() { XmlSchema that = new XmlSchema(); that.attributeFormDefault = this.attributeFormDefault; that.elementFormDefault = this.elementFormDefault; that.blockDefault = this.blockDefault; that.finalDefault = this.finalDefault; that.targetNs = this.targetNs; that.version = this.version; that.isPreprocessed = this.isPreprocessed; //that.IsProcessing = this.IsProcessing; //Not sure if this is needed //Clone its Items for (int i = 0; i < this.items.Count; ++i) { XmlSchemaObject newItem; XmlSchemaComplexType complexType; XmlSchemaElement element; XmlSchemaGroup group; if ((complexType = items[i] as XmlSchemaComplexType) != null) { newItem = complexType.Clone(this); } else if ((element = items[i] as XmlSchemaElement) != null) { newItem = element.Clone(this); } else if ((group = items[i] as XmlSchemaGroup) != null) { newItem = group.Clone(this); } else { newItem = items[i].Clone(); } that.Items.Add(newItem); } //Clone Includes for (int i = 0; i < this.includes.Count; ++i) { XmlSchemaExternal newInclude = (XmlSchemaExternal)this.includes[i].Clone(); that.Includes.Add(newInclude); } that.Namespaces = this.Namespaces; //that.includes = this.includes; //Need to verify this is OK for redefines that.BaseUri = this.BaseUri; return that; }
public static bool ValidateXmlToSchema(string ovffilename) { bool isValid = false; string currentPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); string xmlNamespaceSchemaFilename = Path.Combine(currentPath, Properties.Settings.Default.xmlNamespaceSchemaLocation); string cimCommonSchemaFilename = Path.Combine(currentPath, Properties.Settings.Default.cimCommonSchemaLocation); string cimRASDSchemaFilename = Path.Combine(currentPath, Properties.Settings.Default.cimRASDSchemaLocation); string cimVSSDSchemaFilename = Path.Combine(currentPath, Properties.Settings.Default.cimVSSDSchemaLocation); string ovfSchemaFilename = Path.Combine(currentPath, Properties.Settings.Default.ovfEnvelopeSchemaLocation); string wsseSchemaFilename = Path.Combine(currentPath, Properties.Settings.Default.wsseSchemaLocation); string xencSchemaFilename = Path.Combine(currentPath, Properties.Settings.Default.xencSchemaLocation); string wsuSchemaFilename = Path.Combine(currentPath, Properties.Settings.Default.wsuSchemaLocation); string xmldsigSchemaFilename = Path.Combine(currentPath, Properties.Settings.Default.xmldsigSchemaLocation); // Allow use of xmlStream in finally block. FileStream xmlStream = null; try { string ovfname = ovffilename; string ext = Path.GetExtension(ovffilename); if (!string.IsNullOrEmpty(ext) && (ext.ToLower().EndsWith("gz") || ext.ToLower().EndsWith("bz2"))) { ovfname = Path.GetFileNameWithoutExtension(ovffilename); } ext = Path.GetExtension(ovfname); if (!string.IsNullOrEmpty(ext) && ext.ToLower().EndsWith("ova")) { ovfname = Path.GetFileNameWithoutExtension(ovfname) + ".ovf"; } ext = Path.GetExtension(ovfname); if (!ext.ToLower().EndsWith("ovf")) { throw new InvalidDataException("OVF.ValidateXmlToSchema: Incorrect filename: " + ovfname); } xmlStream = new FileStream(ovfname, FileMode.Open, FileAccess.Read, FileShare.Read); XmlReaderSettings settings = new XmlReaderSettings(); settings.DtdProcessing = DtdProcessing.Parse; //Upgrading to .Net 4.0: ProhibitDtd=false is obsolete, this line is the replacement according to: http://msdn.microsoft.com/en-us/library/system.xml.xmlreadersettings.prohibitdtd%28v=vs.100%29.aspx XmlSchema schema = new XmlSchema(); bool useOnlineSchema = Convert.ToBoolean(Properties.Settings.Default.useOnlineSchema); if (useOnlineSchema) { settings.Schemas.Add(null, Properties.Settings.Default.dsp8023OnlineSchema); } else { settings.Schemas.Add("http://www.w3.org/XML/1998/namespace", xmlNamespaceSchemaFilename); settings.Schemas.Add("http://schemas.dmtf.org/wbem/wscim/1/common", cimCommonSchemaFilename); settings.Schemas.Add("http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_VirtualSystemSettingData", cimVSSDSchemaFilename); settings.Schemas.Add("http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData", cimRASDSchemaFilename); settings.Schemas.Add("http://schemas.dmtf.org/ovf/envelope/1", ovfSchemaFilename); settings.Schemas.Add("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", wsseSchemaFilename); settings.Schemas.Add("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd", wsuSchemaFilename); //settings.Schemas.Add("http://www.w3.org/2001/04/xmlenc#", xencSchemaFilename); //settings.Schemas.Add("http://www.w3.org/2000/09/xmldsig#", xmldsigSchemaFilename); } settings.ValidationType = ValidationType.Schema; XmlReader reader = XmlReader.Create(xmlStream, settings); while (reader.Read()) { } isValid = true; } catch (XmlException xmlex) { log.ErrorFormat("ValidateXmlToSchema XML Exception: {0}", xmlex.Message); throw new Exception(xmlex.Message, xmlex); } catch (XmlSchemaException schemaex) { log.ErrorFormat("ValidateXmlToSchema Schema Exception: {0}", schemaex.Message); throw new Exception(schemaex.Message, schemaex); } catch (Exception ex) { log.ErrorFormat("ValidateXmlToSchema Exception: {0}", ex.Message); throw new Exception(ex.Message, ex); } finally { xmlStream.Close(); } return(isValid); }
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(); }
public static void Add(this XmlSchema that, XmlSchemaType ty) { that.Items.Add(ty); }