private void CreateSimpletypeLength(string length, string minLength, string maxLength, bool expected) { passed = true; XmlSchema schema = new XmlSchema(); XmlSchemaSimpleType testType = new XmlSchemaSimpleType(); testType.Name = "TestType"; XmlSchemaSimpleTypeRestriction testTypeRestriction = new XmlSchemaSimpleTypeRestriction(); testTypeRestriction.BaseTypeName = new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema"); if (length != "-") { XmlSchemaLengthFacet _length = new XmlSchemaLengthFacet(); _length.Value = length; testTypeRestriction.Facets.Add(_length); } if (minLength != "-") { XmlSchemaMinLengthFacet _minLength = new XmlSchemaMinLengthFacet(); _minLength.Value = minLength; testTypeRestriction.Facets.Add(_minLength); } if (maxLength != "-") { XmlSchemaMaxLengthFacet _maxLength = new XmlSchemaMaxLengthFacet(); _maxLength.Value = maxLength; testTypeRestriction.Facets.Add(_maxLength); } testType.Content = testTypeRestriction; schema.Items.Add(testType); schema.Compile(new ValidationEventHandler(ValidationCallbackOne)); Assert.IsTrue (expected == passed, (passed ? "Test passed, should have failed" : "Test failed, should have passed") + ": " + length + " " + minLength + " " + maxLength); }
/// <summary> /// Returns a simple type which extends the basic datatype and /// restricts is using the string validator /// </summary> public override XmlSchemaSimpleType GetSimpleType(string attributeDataType) { var retVal = base.GetSimpleType(attributeDataType); var restriction = (XmlSchemaSimpleTypeRestriction) retVal.Content; var sva = (StringValidatorAttribute) Attribute; if (!string.IsNullOrEmpty(sva.InvalidCharacters)) { var pFacet = new XmlSchemaPatternFacet { Value = sva.InvalidCharacters }; // TODO: convert this to a regex that excludes the characters pFacet.Value = string.Format( "[^{0}]*", pFacet.Value .Replace(@"\", @"\\") .Replace(@"[", @"\[") .Replace(@"]", @"\]")); restriction.Facets.Add(pFacet); } var minFacet = new XmlSchemaMinLengthFacet { Value = sva.MinLength.ToString() }; restriction.Facets.Add(minFacet); var maxFacet = new XmlSchemaMaxLengthFacet { Value = sva.MaxLength.ToString() }; restriction.Facets.Add(maxFacet); return retVal; }
internal static XmlSchemaSimpleContentRestriction Read(XmlSchemaReader reader, ValidationEventHandler h) { XmlSchemaSimpleContentRestriction xmlSchemaSimpleContentRestriction = new XmlSchemaSimpleContentRestriction(); reader.MoveToElement(); if (reader.NamespaceURI != "http://www.w3.org/2001/XMLSchema" || reader.LocalName != "restriction") { XmlSchemaObject.error(h, "Should not happen :1: XmlSchemaComplexContentRestriction.Read, name=" + reader.Name, null); reader.SkipToEnd(); return(null); } xmlSchemaSimpleContentRestriction.LineNumber = reader.LineNumber; xmlSchemaSimpleContentRestriction.LinePosition = reader.LinePosition; xmlSchemaSimpleContentRestriction.SourceUri = reader.BaseURI; while (reader.MoveToNextAttribute()) { if (reader.Name == "base") { Exception ex; xmlSchemaSimpleContentRestriction.baseTypeName = XmlSchemaUtil.ReadQNameAttribute(reader, out ex); if (ex != null) { XmlSchemaObject.error(h, reader.Value + " is not a valid value for base attribute", ex); } } else if (reader.Name == "id") { xmlSchemaSimpleContentRestriction.Id = reader.Value; } else if ((reader.NamespaceURI == string.Empty && reader.Name != "xmlns") || reader.NamespaceURI == "http://www.w3.org/2001/XMLSchema") { XmlSchemaObject.error(h, reader.Name + " is not a valid attribute for restriction", null); } else { XmlSchemaUtil.ReadUnhandledAttribute(reader, xmlSchemaSimpleContentRestriction); } } reader.MoveToElement(); if (reader.IsEmptyElement) { return(xmlSchemaSimpleContentRestriction); } int num = 1; while (reader.ReadNextElement()) { if (reader.NodeType == XmlNodeType.EndElement) { if (reader.LocalName != "restriction") { XmlSchemaObject.error(h, "Should not happen :2: XmlSchemaSimpleContentRestriction.Read, name=" + reader.Name, null); } break; } if (num <= 1 && reader.LocalName == "annotation") { num = 2; XmlSchemaAnnotation xmlSchemaAnnotation = XmlSchemaAnnotation.Read(reader, h); if (xmlSchemaAnnotation != null) { xmlSchemaSimpleContentRestriction.Annotation = xmlSchemaAnnotation; } } else if (num <= 2 && reader.LocalName == "simpleType") { num = 3; XmlSchemaSimpleType xmlSchemaSimpleType = XmlSchemaSimpleType.Read(reader, h); if (xmlSchemaSimpleType != null) { xmlSchemaSimpleContentRestriction.baseType = xmlSchemaSimpleType; } } else { if (num <= 3) { if (reader.LocalName == "minExclusive") { num = 3; XmlSchemaMinExclusiveFacet xmlSchemaMinExclusiveFacet = XmlSchemaMinExclusiveFacet.Read(reader, h); if (xmlSchemaMinExclusiveFacet != null) { xmlSchemaSimpleContentRestriction.facets.Add(xmlSchemaMinExclusiveFacet); } continue; } if (reader.LocalName == "minInclusive") { num = 3; XmlSchemaMinInclusiveFacet xmlSchemaMinInclusiveFacet = XmlSchemaMinInclusiveFacet.Read(reader, h); if (xmlSchemaMinInclusiveFacet != null) { xmlSchemaSimpleContentRestriction.facets.Add(xmlSchemaMinInclusiveFacet); } continue; } if (reader.LocalName == "maxExclusive") { num = 3; XmlSchemaMaxExclusiveFacet xmlSchemaMaxExclusiveFacet = XmlSchemaMaxExclusiveFacet.Read(reader, h); if (xmlSchemaMaxExclusiveFacet != null) { xmlSchemaSimpleContentRestriction.facets.Add(xmlSchemaMaxExclusiveFacet); } continue; } if (reader.LocalName == "maxInclusive") { num = 3; XmlSchemaMaxInclusiveFacet xmlSchemaMaxInclusiveFacet = XmlSchemaMaxInclusiveFacet.Read(reader, h); if (xmlSchemaMaxInclusiveFacet != null) { xmlSchemaSimpleContentRestriction.facets.Add(xmlSchemaMaxInclusiveFacet); } continue; } if (reader.LocalName == "totalDigits") { num = 3; XmlSchemaTotalDigitsFacet xmlSchemaTotalDigitsFacet = XmlSchemaTotalDigitsFacet.Read(reader, h); if (xmlSchemaTotalDigitsFacet != null) { xmlSchemaSimpleContentRestriction.facets.Add(xmlSchemaTotalDigitsFacet); } continue; } if (reader.LocalName == "fractionDigits") { num = 3; XmlSchemaFractionDigitsFacet xmlSchemaFractionDigitsFacet = XmlSchemaFractionDigitsFacet.Read(reader, h); if (xmlSchemaFractionDigitsFacet != null) { xmlSchemaSimpleContentRestriction.facets.Add(xmlSchemaFractionDigitsFacet); } continue; } if (reader.LocalName == "length") { num = 3; XmlSchemaLengthFacet xmlSchemaLengthFacet = XmlSchemaLengthFacet.Read(reader, h); if (xmlSchemaLengthFacet != null) { xmlSchemaSimpleContentRestriction.facets.Add(xmlSchemaLengthFacet); } continue; } if (reader.LocalName == "minLength") { num = 3; XmlSchemaMinLengthFacet xmlSchemaMinLengthFacet = XmlSchemaMinLengthFacet.Read(reader, h); if (xmlSchemaMinLengthFacet != null) { xmlSchemaSimpleContentRestriction.facets.Add(xmlSchemaMinLengthFacet); } continue; } if (reader.LocalName == "maxLength") { num = 3; XmlSchemaMaxLengthFacet xmlSchemaMaxLengthFacet = XmlSchemaMaxLengthFacet.Read(reader, h); if (xmlSchemaMaxLengthFacet != null) { xmlSchemaSimpleContentRestriction.facets.Add(xmlSchemaMaxLengthFacet); } continue; } if (reader.LocalName == "enumeration") { num = 3; XmlSchemaEnumerationFacet xmlSchemaEnumerationFacet = XmlSchemaEnumerationFacet.Read(reader, h); if (xmlSchemaEnumerationFacet != null) { xmlSchemaSimpleContentRestriction.facets.Add(xmlSchemaEnumerationFacet); } continue; } if (reader.LocalName == "whiteSpace") { num = 3; XmlSchemaWhiteSpaceFacet xmlSchemaWhiteSpaceFacet = XmlSchemaWhiteSpaceFacet.Read(reader, h); if (xmlSchemaWhiteSpaceFacet != null) { xmlSchemaSimpleContentRestriction.facets.Add(xmlSchemaWhiteSpaceFacet); } continue; } if (reader.LocalName == "pattern") { num = 3; XmlSchemaPatternFacet xmlSchemaPatternFacet = XmlSchemaPatternFacet.Read(reader, h); if (xmlSchemaPatternFacet != null) { xmlSchemaSimpleContentRestriction.facets.Add(xmlSchemaPatternFacet); } continue; } } if (num <= 4) { if (reader.LocalName == "attribute") { num = 4; XmlSchemaAttribute xmlSchemaAttribute = XmlSchemaAttribute.Read(reader, h); if (xmlSchemaAttribute != null) { xmlSchemaSimpleContentRestriction.Attributes.Add(xmlSchemaAttribute); } continue; } if (reader.LocalName == "attributeGroup") { num = 4; XmlSchemaAttributeGroupRef xmlSchemaAttributeGroupRef = XmlSchemaAttributeGroupRef.Read(reader, h); if (xmlSchemaAttributeGroupRef != null) { xmlSchemaSimpleContentRestriction.attributes.Add(xmlSchemaAttributeGroupRef); } continue; } } if (num <= 5 && reader.LocalName == "anyAttribute") { num = 6; XmlSchemaAnyAttribute xmlSchemaAnyAttribute = XmlSchemaAnyAttribute.Read(reader, h); if (xmlSchemaAnyAttribute != null) { xmlSchemaSimpleContentRestriction.AnyAttribute = xmlSchemaAnyAttribute; } } else { reader.RaiseInvalidElementError(); } } } return(xmlSchemaSimpleContentRestriction); }
//<restriction //base = QName //id = ID //{any attributes with non-schema namespace . . .}> //Content: (annotation?, (simpleType?, (minExclusive | minInclusive | maxExclusive | maxInclusive | totalDigits | fractionDigits | length | minLength | maxLength | enumeration | whiteSpace | pattern)*)?, ((attribute | attributeGroup)*, anyAttribute?)) //</restriction> internal static XmlSchemaSimpleContentRestriction Read(XmlSchemaReader reader, ValidationEventHandler h) { XmlSchemaSimpleContentRestriction restriction = new XmlSchemaSimpleContentRestriction(); reader.MoveToElement(); if (reader.NamespaceURI != XmlSchema.Namespace || reader.LocalName != xmlname) { error(h, "Should not happen :1: XmlSchemaComplexContentRestriction.Read, name=" + reader.Name, null); reader.SkipToEnd(); return(null); } restriction.LineNumber = reader.LineNumber; restriction.LinePosition = reader.LinePosition; restriction.SourceUri = reader.BaseURI; while (reader.MoveToNextAttribute()) { if (reader.Name == "base") { Exception innerex; restriction.baseTypeName = XmlSchemaUtil.ReadQNameAttribute(reader, out innerex); if (innerex != null) { error(h, reader.Value + " is not a valid value for base attribute", innerex); } } else if (reader.Name == "id") { restriction.Id = reader.Value; } else if ((reader.NamespaceURI == "" && reader.Name != "xmlns") || reader.NamespaceURI == XmlSchema.Namespace) { error(h, reader.Name + " is not a valid attribute for restriction", null); } else { XmlSchemaUtil.ReadUnhandledAttribute(reader, restriction); } } reader.MoveToElement(); if (reader.IsEmptyElement) { return(restriction); } //Content: 1.annotation?, // 2.simpleType?, // 3.(minExclusive |...| enumeration | whiteSpace | pattern)*, // 4.(attribute | attributeGroup)*, // 5.anyAttribute? int level = 1; while (reader.ReadNextElement()) { if (reader.NodeType == XmlNodeType.EndElement) { if (reader.LocalName != xmlname) { error(h, "Should not happen :2: XmlSchemaSimpleContentRestriction.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) { restriction.Annotation = annotation; } continue; } if (level <= 2 && reader.LocalName == "simpleType") { level = 3; XmlSchemaSimpleType stype = XmlSchemaSimpleType.Read(reader, h); if (stype != null) { restriction.baseType = stype; } continue; } if (level <= 3) { if (reader.LocalName == "minExclusive") { level = 3; XmlSchemaMinExclusiveFacet minex = XmlSchemaMinExclusiveFacet.Read(reader, h); if (minex != null) { restriction.facets.Add(minex); } continue; } else if (reader.LocalName == "minInclusive") { level = 3; XmlSchemaMinInclusiveFacet mini = XmlSchemaMinInclusiveFacet.Read(reader, h); if (mini != null) { restriction.facets.Add(mini); } continue; } else if (reader.LocalName == "maxExclusive") { level = 3; XmlSchemaMaxExclusiveFacet maxex = XmlSchemaMaxExclusiveFacet.Read(reader, h); if (maxex != null) { restriction.facets.Add(maxex); } continue; } else if (reader.LocalName == "maxInclusive") { level = 3; XmlSchemaMaxInclusiveFacet maxi = XmlSchemaMaxInclusiveFacet.Read(reader, h); if (maxi != null) { restriction.facets.Add(maxi); } continue; } else if (reader.LocalName == "totalDigits") { level = 3; XmlSchemaTotalDigitsFacet total = XmlSchemaTotalDigitsFacet.Read(reader, h); if (total != null) { restriction.facets.Add(total); } continue; } else if (reader.LocalName == "fractionDigits") { level = 3; XmlSchemaFractionDigitsFacet fraction = XmlSchemaFractionDigitsFacet.Read(reader, h); if (fraction != null) { restriction.facets.Add(fraction); } continue; } else if (reader.LocalName == "length") { level = 3; XmlSchemaLengthFacet length = XmlSchemaLengthFacet.Read(reader, h); if (length != null) { restriction.facets.Add(length); } continue; } else if (reader.LocalName == "minLength") { level = 3; XmlSchemaMinLengthFacet minlen = XmlSchemaMinLengthFacet.Read(reader, h); if (minlen != null) { restriction.facets.Add(minlen); } continue; } else if (reader.LocalName == "maxLength") { level = 3; XmlSchemaMaxLengthFacet maxlen = XmlSchemaMaxLengthFacet.Read(reader, h); if (maxlen != null) { restriction.facets.Add(maxlen); } continue; } else if (reader.LocalName == "enumeration") { level = 3; XmlSchemaEnumerationFacet enumeration = XmlSchemaEnumerationFacet.Read(reader, h); if (enumeration != null) { restriction.facets.Add(enumeration); } continue; } else if (reader.LocalName == "whiteSpace") { level = 3; XmlSchemaWhiteSpaceFacet ws = XmlSchemaWhiteSpaceFacet.Read(reader, h); if (ws != null) { restriction.facets.Add(ws); } continue; } else if (reader.LocalName == "pattern") { level = 3; XmlSchemaPatternFacet pattern = XmlSchemaPatternFacet.Read(reader, h); if (pattern != null) { restriction.facets.Add(pattern); } continue; } } if (level <= 4) { if (reader.LocalName == "attribute") { level = 4; XmlSchemaAttribute attr = XmlSchemaAttribute.Read(reader, h); if (attr != null) { restriction.Attributes.Add(attr); } continue; } if (reader.LocalName == "attributeGroup") { level = 4; XmlSchemaAttributeGroupRef attr = XmlSchemaAttributeGroupRef.Read(reader, h); if (attr != null) { restriction.attributes.Add(attr); } continue; } } if (level <= 5 && reader.LocalName == "anyAttribute") { level = 6; XmlSchemaAnyAttribute anyattr = XmlSchemaAnyAttribute.Read(reader, h); if (anyattr != null) { restriction.AnyAttribute = anyattr; } continue; } reader.RaiseInvalidElementError(); } return(restriction); }
protected override void Visit(XmlSchemaMaxLengthFacet facet) { AddLeaf(SimpleTypeStructureNodeType.FacetMaxLength, facet); }
//<maxLength // fixed = boolean : false // id = ID // value = nonNegativeInteger // {any attributes with non-schema namespace . . .}> // Content: (annotation?) //</maxLength> internal static XmlSchemaMaxLengthFacet Read(XmlSchemaReader reader, ValidationEventHandler h) { XmlSchemaMaxLengthFacet length = new XmlSchemaMaxLengthFacet(); reader.MoveToElement(); if (reader.NamespaceURI != XmlSchema.Namespace || reader.LocalName != xmlname) { error(h, "Should not happen :1: XmlSchemaMaxLengthFacet.Read, name=" + reader.Name, null); reader.Skip(); return(null); } length.LineNumber = reader.LineNumber; length.LinePosition = reader.LinePosition; length.SourceUri = reader.BaseURI; while (reader.MoveToNextAttribute()) { if (reader.Name == "id") { length.Id = reader.Value; } else if (reader.Name == "fixed") { Exception innerex; length.IsFixed = XmlSchemaUtil.ReadBoolAttribute(reader, out innerex); if (innerex != null) { error(h, reader.Value + " is not a valid value for fixed attribute", innerex); } } else if (reader.Name == "value") { length.Value = reader.Value; } else if ((reader.NamespaceURI == "" && reader.Name != "xmlns") || reader.NamespaceURI == XmlSchema.Namespace) { error(h, reader.Name + " is not a valid attribute for group", null); } else { XmlSchemaUtil.ReadUnhandledAttribute(reader, length); } } reader.MoveToElement(); if (reader.IsEmptyElement) { return(length); } // Content: (annotation?) int level = 1; while (reader.ReadNextElement()) { if (reader.NodeType == XmlNodeType.EndElement) { if (reader.LocalName != xmlname) { error(h, "Should not happen :2: XmlSchemaMaxLengthFacet.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) { length.Annotation = annotation; } continue; } reader.RaiseInvalidElementError(); } return(length); }
private void checkMaxLengthFacet(XmlSchemaMaxLengthFacet maxlf, XmlSchemaFacet.Facet facetsDefined, ValidationEventHandler h) { if (maxlf != null) { try { if ((facetsDefined & XmlSchemaFacet.Facet.length) != 0) maxlf.error(h, "It is an error for both length and minLength or maxLength to be present."); else { decimal newMaxLengthFacet = decimal.Parse (maxlf.Value.Trim (), lengthStyle, CultureInfo.InvariantCulture); if (((fixedFacets & XmlSchemaFacet.Facet.maxLength)!=0) && (newMaxLengthFacet != maxLengthFacet)) maxlf.error(h, String.Format(CultureInfo.InvariantCulture, "The value '{0}' is not the same as the fixed value '{1}' on the base type", maxlf.Value.Trim (), maxLengthFacet)); if ((maxLengthFacet >0) && (newMaxLengthFacet > maxLengthFacet)) maxlf.error(h, String.Format(CultureInfo.InvariantCulture, "The value '{0}' is not a valid restriction of the value '{1}' on the base maxLength facet", maxlf.Value.Trim (), maxLengthFacet)); else maxLengthFacet = newMaxLengthFacet; if (maxLengthFacet < 0) maxlf.error(h, "The value '" + maxLengthFacet + "' is an invalid maxLength"); if (minLengthFacet >=0 && minLengthFacet > maxLengthFacet) maxlf.error(h, "minLength is greater than maxLength."); } } catch (FormatException) { maxlf.error (h, "The value '" + maxlf.Value+ "' is an invalid maxLength facet specification"); } } }
protected virtual void Visit(XmlSchemaMaxLengthFacet facet) { }
public XsdSimpleRestrictionType (RelaxngDatatype primitive, RelaxngParamList parameters) { type = new XmlSchemaSimpleType (); XmlSchemaSimpleTypeRestriction r = new XmlSchemaSimpleTypeRestriction (); type.Content = r; string ns = primitive.NamespaceURI; // Remap XML Schema datatypes namespace -> XML Schema namespace. if (ns == "http://www.w3.org/2001/XMLSchema-datatypes") ns = XSchema.Namespace; r.BaseTypeName = new XmlQualifiedName (primitive.Name, ns); foreach (RelaxngParam p in parameters) { XmlSchemaFacet f = null; string value = p.Value; switch (p.Name) { case "maxExclusive": f = new XmlSchemaMaxExclusiveFacet (); break; case "maxInclusive": f = new XmlSchemaMaxInclusiveFacet (); break; case "minExclusive": f = new XmlSchemaMinExclusiveFacet (); break; case "minInclusive": f = new XmlSchemaMinInclusiveFacet (); break; case "pattern": f = new XmlSchemaPatternFacet (); // .NET/Mono Regex has a bug that it does not support "IsLatin-1Supplement" // (it somehow breaks at '-'). value = value.Replace ("\\p{IsLatin-1Supplement}", "[\\x80-\\xFF]"); break; case "whiteSpace": f = new XmlSchemaWhiteSpaceFacet (); break; case "length": f = new XmlSchemaLengthFacet (); break; case "maxLength": f = new XmlSchemaMaxLengthFacet (); break; case "minLength": f = new XmlSchemaMinLengthFacet (); break; case "fractionDigits": f = new XmlSchemaFractionDigitsFacet (); break; case "totalDigits": f = new XmlSchemaTotalDigitsFacet (); break; default: throw new RelaxngException (String.Format ("XML Schema facet {0} is not recognized or not supported.", p.Name)); } f.Value = value; r.Facets.Add (f); } // Now we create XmlSchema to handle simple-type // based validation (since there is no other way, // because of sucky XmlSchemaSimpleType design). schema = new XSchema (); XmlSchemaElement el = new XmlSchemaElement (); el.Name = "root"; el.SchemaType = type; schema.Items.Add (el); schema.Compile (null); }
internal static XmlSchemaMaxLengthFacet Read(XmlSchemaReader reader, ValidationEventHandler h) { XmlSchemaMaxLengthFacet xmlSchemaMaxLengthFacet = new XmlSchemaMaxLengthFacet(); reader.MoveToElement(); if (reader.NamespaceURI != "http://www.w3.org/2001/XMLSchema" || reader.LocalName != "maxLength") { XmlSchemaObject.error(h, "Should not happen :1: XmlSchemaMaxLengthFacet.Read, name=" + reader.Name, null); reader.Skip(); return(null); } xmlSchemaMaxLengthFacet.LineNumber = reader.LineNumber; xmlSchemaMaxLengthFacet.LinePosition = reader.LinePosition; xmlSchemaMaxLengthFacet.SourceUri = reader.BaseURI; while (reader.MoveToNextAttribute()) { if (reader.Name == "id") { xmlSchemaMaxLengthFacet.Id = reader.Value; } else if (reader.Name == "fixed") { Exception ex; xmlSchemaMaxLengthFacet.IsFixed = XmlSchemaUtil.ReadBoolAttribute(reader, out ex); if (ex != null) { XmlSchemaObject.error(h, reader.Value + " is not a valid value for fixed attribute", ex); } } else if (reader.Name == "value") { xmlSchemaMaxLengthFacet.Value = reader.Value; } else if ((reader.NamespaceURI == string.Empty && reader.Name != "xmlns") || reader.NamespaceURI == "http://www.w3.org/2001/XMLSchema") { XmlSchemaObject.error(h, reader.Name + " is not a valid attribute for group", null); } else { XmlSchemaUtil.ReadUnhandledAttribute(reader, xmlSchemaMaxLengthFacet); } } reader.MoveToElement(); if (reader.IsEmptyElement) { return(xmlSchemaMaxLengthFacet); } int num = 1; while (reader.ReadNextElement()) { if (reader.NodeType == XmlNodeType.EndElement) { if (reader.LocalName != "maxLength") { XmlSchemaObject.error(h, "Should not happen :2: XmlSchemaMaxLengthFacet.Read, name=" + reader.Name, null); } break; } if (num <= 1 && reader.LocalName == "annotation") { num = 2; XmlSchemaAnnotation xmlSchemaAnnotation = XmlSchemaAnnotation.Read(reader, h); if (xmlSchemaAnnotation != null) { xmlSchemaMaxLengthFacet.Annotation = xmlSchemaAnnotation; } } else { reader.RaiseInvalidElementError(); } } return(xmlSchemaMaxLengthFacet); }
//<maxLength // fixed = boolean : false // id = ID // value = nonNegativeInteger // {any attributes with non-schema namespace . . .}> // Content: (annotation?) //</maxLength> internal static XmlSchemaMaxLengthFacet Read(XmlSchemaReader reader, ValidationEventHandler h) { XmlSchemaMaxLengthFacet length = new XmlSchemaMaxLengthFacet(); reader.MoveToElement(); if(reader.NamespaceURI != XmlSchema.Namespace || reader.LocalName != xmlname) { error(h,"Should not happen :1: XmlSchemaMaxLengthFacet.Read, name="+reader.Name,null); reader.Skip(); return null; } length.LineNumber = reader.LineNumber; length.LinePosition = reader.LinePosition; length.SourceUri = reader.BaseURI; while(reader.MoveToNextAttribute()) { if(reader.Name == "id") { length.Id = reader.Value; } else if(reader.Name == "fixed") { Exception innerex; length.IsFixed = XmlSchemaUtil.ReadBoolAttribute(reader,out innerex); if(innerex != null) error(h, reader.Value + " is not a valid value for fixed attribute",innerex); } else if(reader.Name == "value") { length.Value = reader.Value; } else if((reader.NamespaceURI == "" && reader.Name != "xmlns") || reader.NamespaceURI == XmlSchema.Namespace) { error(h,reader.Name + " is not a valid attribute for group",null); } else { XmlSchemaUtil.ReadUnhandledAttribute(reader,length); } } reader.MoveToElement(); if(reader.IsEmptyElement) return length; // Content: (annotation?) int level = 1; while(reader.ReadNextElement()) { if(reader.NodeType == XmlNodeType.EndElement) { if(reader.LocalName != xmlname) error(h,"Should not happen :2: XmlSchemaMaxLengthFacet.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) length.Annotation = annotation; continue; } reader.RaiseInvalidElementError(); } return length; }
private void Write22_XmlSchemaMaxLengthFacet(string n, string ns, XmlSchemaMaxLengthFacet o, bool isNullable, bool needType) { if (o == null) { if (isNullable) { base.WriteNullTagLiteral(n, ns); } } else { if (!needType && !(o.GetType() == typeof(XmlSchemaMaxLengthFacet))) { throw base.CreateUnknownTypeException(o); } base.EscapeName = false; base.WriteStartElement(n, ns, o, false, o.Namespaces); if (needType) { base.WriteXsiType("XmlSchemaMaxLengthFacet", "http://www.w3.org/2001/XMLSchema"); } base.WriteAttribute("id", "", o.Id); XmlAttribute[] unhandledAttributes = o.UnhandledAttributes; if (unhandledAttributes != null) { for (int i = 0; i < unhandledAttributes.Length; i++) { XmlAttribute node = unhandledAttributes[i]; base.WriteXmlAttribute(node, o); } } base.WriteAttribute("value", "", o.Value); if (o.IsFixed) { base.WriteAttribute("fixed", "", XmlConvert.ToString(o.IsFixed)); } this.Write11_XmlSchemaAnnotation("annotation", "http://www.w3.org/2001/XMLSchema", o.Annotation, false, false); base.WriteEndElement(o); } }
//[STAThread] //[SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlAppDomain)] static void Main(string[] args) { #region "testing xml" XmlDocument doc = new XmlDocument(); using (XmlWriter xw = doc.CreateNavigator().AppendChild()) { //MemoryStream ms = new MemoryStream(); //XPathDocument xpath = new XPathDocument(ms); //XPathNavigator xpathnav = xpath.CreateNavigator(); //XmlWriter xw = xpathnav.AppendChild(); xw.WriteStartDocument(); xw.WriteStartElement("Page"); xw.WriteStartElement("Line"); xw.WriteStartElement("Word"); xw.WriteString("first line."); xw.WriteEndElement(); xw.WriteEndElement(); xw.WriteStartElement("Line"); xw.WriteStartElement("Word"); xw.WriteString("A SECOND WORD!!"); xw.WriteEndElement(); xw.WriteEndElement(); xw.WriteEndElement(); //page xw.WriteEndDocument(); } StringWriter ms = new StringWriter(); XmlWriterSettings setting = new XmlWriterSettings { ConformanceLevel = ConformanceLevel.Auto }; XmlWriter newXW = XmlWriter.Create(ms); XslCompiledTransform xslt = new XslCompiledTransform(); xslt.Load("test.xslt"); XmlNode root = doc.SelectSingleNode("/*"); XPathNavigator xpath = root.CreateNavigator(); //xslt.Transform(xpath, newXW); xslt.Transform(doc, null, ms); Console.WriteLine(ms.ToString()); Environment.Exit(0); #endregion #region "testing Vector" //Vector v1 = new Vector(1f, 1f, 1f); //Vector v2 = new Vector(3f, 2f, 1f); //Vector result = v2.Subtract(v1); //Console.WriteLine(result[0]); //Console.WriteLine(result[1]); //Console.WriteLine(result[2]); //Console.WriteLine(Math.Atan2(1d, 1d)*180/Math.PI); //Environment.Exit(0); #endregion #region "testing data structures" //Stack<int> a = new Stack<int>(); //a.Push(2); //a.Push(4); //a.Push(6); //a.Push(8); //a.Pop(); //a.Push(3); //a.Pop(); //a.Push(4); //a.Push(6); //a.Push(7); //a.Pop(); //a.Pop(); //a.Pop(); //Console.WriteLine(a.Pop()); //Environment.Exit(0); #endregion #region //testing merging tiff //List<string> lstImages = new List<string>(); //lstImages.Add(@"C:\Users\janetxue\Downloads\Migration\testing\Corrupted PDF testing\100110.1"); //lstImages.Add(@"C:\Users\janetxue\Downloads\Migration\testing\Corrupted PDF testing\100110.2"); //string strDestinationFileName = @"C:\Users\janetxue\Downloads\Migration\testing\Corrupted PDF testing\merged.tif"; //ImageCodecInfo codec = null; //foreach (ImageCodecInfo cCodec in ImageCodecInfo.GetImageEncoders()) //{ // if (cCodec.CodecName == "Built-in TIFF Codec") // { // codec = cCodec; // break; // } //} //using (EncoderParameters imagePararms = new EncoderParameters(1)) //{ // imagePararms.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.SaveFlag, (long)EncoderValue.MultiFrame); // using (System.Drawing.Image destinationImage = (System.Drawing.Image)(new Bitmap(lstImages[0]))) // { // destinationImage.Save(strDestinationFileName, codec, imagePararms); // imagePararms.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.SaveFlag, (long)EncoderValue.FrameDimensionPage); // for (int i = 1; i < lstImages.Count; i++) // { // using (System.Drawing.Image img = (System.Drawing.Image)(new Bitmap(lstImages[i]))) // { // destinationImage.SaveAdd(img, imagePararms); // } // } // imagePararms.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.SaveFlag, (long)EncoderValue.Flush); // destinationImage.SaveAdd(imagePararms); // } //} //testing corrupted tiff //try //{ // Tiff.SetErrorHandler(new MyTiffErrorHandler()); // using (Tiff image = Tiff.Open(@"C:\Users\janetxue\Downloads\JIT\0409201.DuplicatedImages\20150407.000268\20150407.000268.14.tif", "r")) // { // int numberOfDirectories = image.NumberOfDirectories(); // for (int i = 0; i < numberOfDirectories; ++i) // { // image.SetDirectory((short)i); // int width = image.GetField(TiffTag.IMAGEWIDTH)[0].ToInt(); // int height = image.GetField(TiffTag.IMAGELENGTH)[0].ToInt(); // int imageSize = height * width; // int[] raster = new int[imageSize]; // if (!image.ReadRGBAImage(width, height, raster, true)) // { // Console.WriteLine("Page " + i + " is corrupted"); // continue; // } // } // } // Console.WriteLine("Passed"); //} //catch (Exception e) //{ // Console.WriteLine("Oops"); //} //Console.ReadKey(); //testing corrupted pdf //string path1 = @"C:\Users\janetxue\Downloads\Migration\testing\Corrupted PDF testing\100110.1"; //string path2 = @"C:\Users\janetxue\Downloads\Migration\testing\Corrupted PDF testing\100110.2"; //string path3 = @"C:\Users\janetxue\Downloads\Migration\testing\Corrupted PDF testing\merged.pdf"; //string path4 = @"C:\Users\janetxue\Downloads\Migration\testing\Corrupted PDF testing\corrupted.pdf"; //try //{ // //FileStream fs = new FileStream(path3, FileMode.Create, FileAccess.Write, FileShare.None); // //Document doc = new Document(PageSize.LETTER, 0, 0, 0, 0); // //PdfWriter writer = PdfWriter.GetInstance(doc, fs); // //doc.Open(); // //iTextSharp.text.Image tiff = iTextSharp.text.Image.GetInstance(path1); // //tiff.ScaleToFit(doc.PageSize.Width, doc.PageSize.Height); // //doc.Add(tiff); // //doc.NewPage(); // //tiff = iTextSharp.text.Image.GetInstance(path2); // //tiff.ScaleToFit(doc.PageSize.Width, doc.PageSize.Height); // //doc.Add(tiff); // //doc.Close(); // //fs.Close(); // using (FileStream fs = new FileStream(path3, FileMode.Create, FileAccess.Write, FileShare.None)) // using (Document doc = new Document(PageSize.LETTER, 0, 0, 0, 0)) // { // PdfWriter writer = PdfWriter.GetInstance(doc, fs); // doc.Open(); // iTextSharp.text.Image tiff = iTextSharp.text.Image.GetInstance(path1); // tiff.ScaleToFit(doc.PageSize.Width, doc.PageSize.Height); // doc.Add(tiff); // doc.NewPage(); // } // PdfReader pdfReader = new PdfReader(path4); // int num = pdfReader.NumberOfPages; // Console.WriteLine(num); // Console.ReadKey(); //} //catch (PdfException e1) //{ // Console.WriteLine("can't"); // Console.ReadKey(); //} //catch (Exception e2) //{ // Console.WriteLine("gotch ya"); // Console.ReadKey(); //} //testing threading //AppDomain currentDomain = AppDomain.CurrentDomain; //currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler); //try //{ // thread1 = new Thread(new ThreadStart(() => initDatabase("1st thread"))); // thread2 = new Thread(new ThreadStart(() => initDatabase("2nd thread"))); // thread1.Start(); // thread2.Start(); // Console.WriteLine(thread1.ThreadState); // thread1.Join(); // thread2.Join(); // //if (thread1.ThreadState.HasFlag(ThreadState.Aborted) || thread2.ThreadState.HasFlag(ThreadState.Aborted)) // //{ // // Console.WriteLine("gotcha!"); // //} // //else // //{ // // Console.WriteLine("didn't catch it"); // //} //} //catch (Exception) //{ // Console.WriteLine("catch it"); //} //Console.ReadKey(); //testing custom exception //try //{ // throw new PageNumMismatchException(); //} //catch (Exception e) //{ // Console.WriteLine(e.Message); //} //Console.ReadKey(); //testing LINQ //Func<int, bool> myFunc = x => x == 5; //Console.WriteLine(myFunc(5)); //int[] numbers = { 4, 5, 1, 3, 9, 8, 6, 7, 2, 0 }; //IEnumerable<int> firstNumbersLessThan6 = numbers.TakeWhile(n => n < 6); //foreach (int i in firstNumbersLessThan6) // Console.WriteLine(i); //testing miscellaneous //IEnumerable<int> squares = Enumerable.Range(1, 10).Select(x => x * x); //foreach (int i in squares) // Console.WriteLine(i); #endregion #region "testing XML" ////XDocument test = new XDocument( //// new XComment("commenting"), //// new XElement("Root", //// new XElement("child1", "data1"), //// new XElement("child2", "data2"), //// new XElement("child3", //// new XElement("grandChild31", "data31")), //// new XElement("child4", "data4"))); ////test.Save(@"C:\Users\janetxue\Downloads\Others\testing\testing.xml"); //string path = @"C:\Users\Cui\Documents\GitHub\testing\testing\testing\testingXML.xml"; ////shiporderType shiporder; ////XmlSerializer ser = new XmlSerializer(typeof(shiporderType)); ////XmlDocument xml = new XmlDocument(); ////using (StreamReader reader = new StreamReader(path)) ////{ //// xml.Load(reader); //// printXML(xml.DocumentElement); ////} //XmlReader reader = XmlReader.Create(path); //XmlReader reader1 = XmlReader.Create(path); //XmlSchemaSet schemaSet = new XmlSchemaSet(); //XmlSchemaInference inference = new XmlSchemaInference(); //schemaSet = inference.InferSchema(reader); //// Display the inferred schema. //Console.WriteLine("Original schema:\n"); //foreach (XmlSchema schema in schemaSet.Schemas()) //{ // schema.Write(Console.Out); //} //// Use the additional data in item2.xml to refine the original schema. //schemaSet = inference.InferSchema(reader1, schemaSet); //// Display the refined schema. //Console.WriteLine("\n\nRefined schema:\n"); //foreach (XmlSchema schema in schemaSet.Schemas()) //{ // schema.Write(Console.Out); //} ////Console.WriteLine(typeof(MyClass)); ////string path = @"C:\Users\janetxue\Downloads\Others\testing\testing.xml"; ////XDocument test2 = new XDocument(); ////test2 = XDocument.Load(path); ////Console.WriteLine(test2); ////Console.WriteLine(); ////Console.WriteLine("-------------------START HERE-------------------"); ////Console.WriteLine(); //////foreach(XElement el in test2.Descendants("child1")) //////{ ////// Console.WriteLine(el.Value + " " + el.Name); //////} //////Console.WriteLine(); //////Console.WriteLine("-------------------START HERE-------------------"); //////Console.WriteLine(); //////Console.WriteLine(Path.GetDirectoryName(path)); //////Console.WriteLine(test2.Root.Elements().Any()); //////Console.WriteLine(test2.Descendants("child2").Descendants().Any()); //////Console.WriteLine(test2.Descendants("child3").Descendants().Any()); ////Console.WriteLine(test2.Descendants("grandChild31")); #endregion "testing XML" #region "testing Task" //cancelTokenSource = new CancellationTokenSource(); //cancelToken = cancelTokenSource.Token; //log4net.GlobalContext.Properties["LogName"] = "test"; //log = LogUtility.GetLogger(); //Task t1 = null, t2 = null; //t1 = new Task(() => task1()); //t2 = new Task(() => task2()); //if (!Object.ReferenceEquals(t1, null)) // t1.Start(); //if (!Object.ReferenceEquals(t2, null)) // t2.Start(); ////cancelTokenSource.Cancel(); //if (!Object.ReferenceEquals(t1, null)) // t1.Wait(); //if (!Object.ReferenceEquals(t2, null)) // t2.Wait(); //Console.WriteLine("ALL COMPLETE"); //Console.ReadKey(); ////var list = new ConcurrentBag<string>(); ////string[] dirNames = { ".", ".." }; ////List<Task> tasks = new List<Task>(); ////foreach (var dirName in dirNames) ////{ //// Task t = Task.Run(() => //// { //// foreach (var path in Directory.GetFiles(dirName)) //// list.Add(path); //// }); //// tasks.Add(t); ////} ////Task.WaitAll(tasks.ToArray()); ////foreach (Task t in tasks) //// Console.WriteLine("Task {0} Status: {1}", t.Id, t.Status); ////Console.WriteLine("Number of files read: {0}", list.Count); ////foreach (var x in list) //// Console.WriteLine(x); #endregion "testing Task" #region //testing Regex //String tester = @"Root\1/15/2001 (not complete)\Repealed Sections\10-1-1"; //Console.WriteLine(tester + Environment.NewLine); //Console.WriteLine(tester.Replace(@"([\w])", "(in work)") + Environment.NewLine); //Console.WriteLine(Regex.Replace(tester, @"\((.*)\)", "(in work)") + Environment.NewLine); //string pattern = @"\p{Sc}*(\s?\d+[.,]?\d*)\p{Sc}*"; //string replacement = "$"; //string input = "$16.32 12.19 £16.29 €18.29 €18,29"; //string result = Regex.Replace(input, pattern, replacement); //Console.WriteLine(result); //testing compare //String a = "01".Substring(2); //Console.WriteLine(a.Count()); //Console.WriteLine("0".Substring(1)); //Console.WriteLine('1'.CompareTo('2')); //Console.WriteLine('2'.CompareTo('1')); //Console.WriteLine('a'.CompareTo('b')); //Console.WriteLine('b'.CompareTo('a')); //Console.WriteLine('a'.CompareTo('a')); //Console.WriteLine('1'.CompareTo('1')); //Console.WriteLine('1'.CompareTo('z')); //Console.WriteLine('A'.CompareTo('a')); //Console.WriteLine('-'.CompareTo('-')); //Console.WriteLine(''.CompareTo('')); //Console.WriteLine(''.CompareTo('')); //Console.WriteLine(''.CompareTo('')); //testing consol.title //Console.Title = "OhYeah"; //Console.ReadKey(); //Console.Title = "haha"; //testing lambda //String strFolderRoot = @"C:\Users\janetxue\Dropbox\Fairfax Learning files"; ////List<String> lstDocFolders = Directory.GetDirectories(strFolderRoot).ToList(); //List<String> lstDocFolders = Directory.GetDirectories(strFolderRoot).Select(docName => Path.GetFileName(docName)).ToList(); //foreach (String doc in lstDocFolders) //{ // Console.WriteLine(doc); //} //testing path.combine //String root = @"c:\fairfax\"; //int num = 0; //int doc = 12345; //String path = Path.Combine(root, num.ToString(), doc.ToString()); //Console.WriteLine(path); //testing cut/paste //String sourceRoot = @"C:\Users\janetxue\Downloads\Migration\Files\testing\Unmatch Docs\SourceTiff"; //String targetRoot = @"C:\Users\janetxue\Downloads\Migration\Files\testing\Unmatch Docs\TargetPath"; //List<String> lstSourceDocs = Directory.GetDirectories(sourceRoot).ToList(); //foreach (String strSourceDoc in lstSourceDocs) //{ // String strTargetDocPre = strSourceDoc.Replace("SourceTiff", "TargetPath"); // int i = 0; // String strTargetDoc = strTargetDocPre + "." + i; // while (Directory.Exists(strTargetDoc)) // { // strTargetDoc = strTargetDocPre + "." + (++i); // } // Directory.CreateDirectory(strTargetDoc); // List<String> strSourceFiles = Directory.GetFiles(strSourceDoc).ToList(); // foreach(String strSourceFile in strSourceFiles) // { // FileInfo fi = new FileInfo(strSourceFile); // fi.MoveTo(Path.Combine(strTargetDoc, Path.GetFileName(strSourceFile))); // } // Directory.Delete(strSourceDoc); //} //testing remove //String strgroupids = "1234567890"; //Console.WriteLine(strgroupids); //strgroupids = strgroupids.Remove(strgroupids.Length - 2); //for (int i = 0; i < 20; i++) //{ // Console.WriteLine(i % 10); //} //tool sorting //Boolean bExit = false; //while (!bExit) //{ // Console.WriteLine("Input Strings: "); // String sInput = Console.ReadLine(); // List<String> lInput = sInput.Split(new[] {", "}, StringSplitOptions.None).ToList(); // lInput.Sort(); // Console.WriteLine(); // Console.WriteLine("Sorted Strings: "); // foreach (String input in lInput) // { // Console.Write(input + ", "); // } // Console.WriteLine(); // Console.WriteLine("\nDo you want to exit?"); // sInput = Console.ReadLine(); // bExit = (sInput == "y" || sInput == "Y") ? true : false; // Console.WriteLine(); //} //98-361 //int[] bubbleSort = new int[] { 3, 4, 2, 5, 1, 7, 6 }; //for (int i = 0; i < bubbleSort.Length; i++) // for (int j = i + 1; j < bubbleSort.Length; j++) // if (bubbleSort[i] > bubbleSort[j]) // { // int holder = bubbleSort[i]; // bubbleSort[i] = bubbleSort[j]; // bubbleSort[j] = holder; // } //foreach(int x in bubbleSort) //{ // Console.Write(x.ToString() + " "); //} //Console.WriteLine(); //Console.WriteLine("Press any keys to quit."); //Console.ReadKey(); #endregion #region "log4net" //log4net.GlobalContext.Properties["abc"] = "testing"; ////log4net.Config.XmlConfigurator.Configure(); //log = LogHelper.GetLogger(); //log.Info("testing"); //Environment.Exit(0); //log.Debug("Developer: Tutorial was run"); //log.Info("Maintenance: water pump turned on"); //log.Warn("Maintenance: the water pump is getting hot"); //var i = 0; //try //{ // var x = 10 / i; //} //catch(DivideByZeroException ex) //{ // log.Error("Developer: we tried to divide by zero again"); //} //log.Fatal("Maintenance: water pump exploded"); //Console.ReadKey(); #endregion #region "XML Schema" //XmlSchema schema = new XmlSchema(); //// <xs:element name="cat" type="xs: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="xs: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); // Create the FirstName and LastName elements. XmlSchemaElement firstNameElement = new XmlSchemaElement(); firstNameElement.Name = "FirstName"; XmlSchemaElement lastNameElement = new XmlSchemaElement(); lastNameElement.Name = "LastName"; // Create CustomerId attribute. XmlSchemaAttribute idAttribute = new XmlSchemaAttribute(); idAttribute.Name = "CustomerId"; idAttribute.Use = XmlSchemaUse.Required; // Create the simple type for the LastName element. XmlSchemaSimpleType lastNameType = new XmlSchemaSimpleType(); lastNameType.Name = "LastNameType"; XmlSchemaSimpleTypeRestriction lastNameRestriction = new XmlSchemaSimpleTypeRestriction(); lastNameRestriction.BaseTypeName = new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema"); XmlSchemaMaxLengthFacet maxLength = new XmlSchemaMaxLengthFacet(); maxLength.Value = "20"; lastNameRestriction.Facets.Add(maxLength); lastNameType.Content = lastNameRestriction; // Associate the elements and attributes with their types. // Built-in type. firstNameElement.SchemaTypeName = new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema"); // User-defined type. lastNameElement.SchemaTypeName = new XmlQualifiedName("LastNameType", "http://www.tempuri.org"); // Built-in type. idAttribute.SchemaTypeName = new XmlQualifiedName("positiveInteger", "http://www.w3.org/2001/XMLSchema"); // Create the top-level Customer element. XmlSchemaElement customerElement = new XmlSchemaElement(); customerElement.Name = "Customer"; //customerElement.SchemaTypeName = new XmlQualifiedName("ssf"); // Create an anonymous complex type for the Customer element. XmlSchemaComplexType customerType = new XmlSchemaComplexType(); XmlSchemaSequence sequence = new XmlSchemaSequence(); sequence.Items.Add(firstNameElement); sequence.Items.Add(lastNameElement); customerType.Particle = sequence; // Add the CustomerId attribute to the complex type. customerType.Attributes.Add(idAttribute); // Set the SchemaType of the Customer element to // the anonymous complex type created above. customerElement.SchemaType = customerType; // Create an empty schema. XmlSchema customerSchema = new XmlSchema(); //customerSchema.TargetNamespace = "http://www.tempuri.org"; // Add all top-level element and types to the schema customerSchema.Items.Add(customerElement); customerSchema.Items.Add(lastNameType); // Create an XmlSchemaSet to compile the customer schema. //XmlSchemaSet schemaSet = new XmlSchemaSet(); //schemaSet.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); //schemaSet.Add(customerSchema); //schemaSet.Compile(); //foreach (XmlSchema schema in schemaSet.Schemas()) //{ // customerSchema = schema; //} // Write the complete schema to the Console. //customerSchema.Write(Console.Out); XmlWriter writer = XmlWriter.Create(@"C:\Users\janetxue\Downloads\Others\testing\eReg_XML\result.xsd"); customerSchema.Write(writer); #endregion "XML Shcema" }