2005-01-31 Zoltan Varga <vargaz@freemail.hu>
[mono.git] / mcs / class / System.XML / Mono.Xml.Schema / XsdValidatingReader.cs
index 78e4373c28d60e9953de3756d14047b8aad83a01..51cbbcb98c080bd289bcf1fbf7adfac7cbafd4c7 100644 (file)
@@ -6,7 +6,6 @@
 //
 //     (C)2003 Atsushi Enomoto
 //
-//#define IGNORE_KEYS
 
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 using System;
 using System.Collections;
 using System.Collections.Specialized;
+using System.IO;
 using System.Text;
 using System.Xml;
 using System.Xml.Schema;
 using Mono.Xml;
 
+#if NET_2_0
+using ValException = System.Xml.Schema.XmlSchemaValidationException;
+#else
+using ValException = System.Xml.Schema.XmlSchemaException;
+#endif
+
+using QName = System.Xml.XmlQualifiedName;
 using ContentProc = System.Xml.Schema.XmlSchemaContentProcessing;
 using XsElement = System.Xml.Schema.XmlSchemaElement;
 using XsAttribute = System.Xml.Schema.XmlSchemaAttribute;
@@ -61,17 +68,18 @@ namespace Mono.Xml.Schema
                XmlSchemaSet schemas = new XmlSchemaSet ();
                bool namespaces = true;
 
+#region ID Constraints
                bool checkIdentity = true;
-               Hashtable idList = new Hashtable ();
-               ArrayList missingIDReferences;
-               string thisElementId;
+               XsdIDManager idManager = new XsdIDManager ();
+#endregion
 
-#if !IGNORE_KEYS
+#region Key Constraints
+               bool checkKeyConstraints = true;
                ArrayList keyTables = new ArrayList ();
                ArrayList currentKeyFieldConsumers;
                ArrayList tmpKeyrefPool;
+#endregion
                ArrayList elementQNameStack = new ArrayList ();
-#endif
 
                XsdParticleStateManager state = new XsdParticleStateManager ();
 
@@ -84,7 +92,7 @@ namespace Mono.Xml.Schema
                int currentDefaultAttribute = -1;
                ArrayList defaultAttributesCache = new ArrayList ();
                bool defaultAttributeConsumed;
-               XmlQualifiedName attrQName;
+               object currentAttrType;
 
 #region .ctor
                public XsdValidatingReader (XmlReader reader)
@@ -92,25 +100,19 @@ namespace Mono.Xml.Schema
                        this.reader = reader;
                        readerLineInfo = reader as IXmlLineInfo;
                        sourceReaderSchemaInfo = reader as IHasXmlSchemaInfo;
+                       schemas.ValidationEventHandler += ValidationEventHandler;
                }
 #endregion
 
                public ValidationEventHandler ValidationEventHandler;
 
                // Private Properties
-               private XmlQualifiedName CurrentQName {
-                       get {
-                               if (attrQName == null)
-                                       attrQName = new XmlQualifiedName (LocalName, NamespaceURI);
-                               return attrQName;
-                       }
-               }
 
                private XsdValidationContext Context {
                        get { return state.Context; }
                }
 
-#if !IGNORE_KEYS
+#region Key Constraints
                internal ArrayList CurrentKeyFieldConsumers {
                        get {
                                if (currentKeyFieldConsumers == null)
@@ -118,15 +120,7 @@ namespace Mono.Xml.Schema
                                return currentKeyFieldConsumers;
                        }
                }
-#endif
-
-               private ArrayList MissingIDReferences {
-                       get {
-                               if (missingIDReferences == null)
-                                       missingIDReferences = new ArrayList ();
-                               return missingIDReferences;
-                       }
-               }
+#endregion
 
                // Public Non-overrides
 
@@ -139,10 +133,6 @@ namespace Mono.Xml.Schema
                        set { namespaces = value; }
                }
 
-               public XmlReader Reader {
-                       get { return reader; }
-               }
-
                // This is required to resolve xsi:schemaLocation
                public XmlResolver XmlResolver {
                        set {
@@ -172,13 +162,17 @@ namespace Mono.Xml.Schema
                                        else
                                                return SourceReaderSchemaType;
                                case XmlNodeType.Attribute:
-                                       ComplexType ct = Context.ActualType as ComplexType;
-                                       if (ct != null) {
-                                               XsAttribute attdef = ct.AttributeUses [CurrentQName] as XsAttribute;
-                                               if (attdef != null)
-                                                       return attdef.AttributeType;
+                                       if (currentAttrType == null) {
+                                               ComplexType ct = Context.ActualType as ComplexType;
+                                               if (ct != null) {
+                                                       XsAttribute attdef = ct.AttributeUses [new QName (LocalName, NamespaceURI)] as XsAttribute;
+                                                       if (attdef != null)
+                                                               currentAttrType = attdef.AttributeType;
+                                                       return currentAttrType;
+                                               }
+                                               currentAttrType = SourceReaderSchemaType;
                                        }
-                                       return SourceReaderSchemaType;
+                                       return currentAttrType;
                                default:
                                        return SourceReaderSchemaType;
                                }
@@ -221,10 +215,20 @@ namespace Mono.Xml.Schema
 
                // It is used only for independent XmlReader use, not for XmlValidatingReader.
 #if NET_2_0
+               [Obsolete]
                public override object ReadTypedValue ()
 #else
                public object ReadTypedValue ()
 #endif
+               {
+                       object o = XmlSchemaUtil.ReadTypedValue (this,
+                               SchemaType, ParserContext.NamespaceManager,
+                               storedCharacters);
+                       storedCharacters.Length = 0;
+                       return o;
+               }
+               
+               private object ReadTypedValueCore ()
                {
                        XsDatatype dt = SchemaType as XsDatatype;
                        SimpleType st = SchemaType as SimpleType;
@@ -262,7 +266,7 @@ namespace Mono.Xml.Schema
                        return null;
                }
 
-               // Public Overrided Properties
+               // Public Overriden Properties
 
                public override int AttributeCount {
                        get {
@@ -331,11 +335,11 @@ namespace Mono.Xml.Schema
                        get { return GetAttribute (localName, ns); }
                }
 
-               int IXmlLineInfo.LineNumber {
+               public int LineNumber {
                        get { return readerLineInfo != null ? readerLineInfo.LineNumber : 0; }
                }
 
-               int IXmlLineInfo.LinePosition {
+               public int LinePosition {
                        get { return readerLineInfo != null ? readerLineInfo.LinePosition : 0; }
                }
 
@@ -356,7 +360,7 @@ namespace Mono.Xml.Schema
                                if (defaultAttributeConsumed)
                                        return String.Empty;
 
-                               XmlQualifiedName qname = defaultAttributes [currentDefaultAttribute].QualifiedName;
+                               QName qname = defaultAttributes [currentDefaultAttribute].QualifiedName;
                                string prefix = Prefix;
                                if (prefix == String.Empty)
                                        return qname.Name;
@@ -399,7 +403,7 @@ namespace Mono.Xml.Schema
                                        return reader.Prefix;
                                if (defaultAttributeConsumed)
                                        return String.Empty;
-                               XmlQualifiedName qname = defaultAttributes [currentDefaultAttribute].QualifiedName;
+                               QName qname = defaultAttributes [currentDefaultAttribute].QualifiedName;
                                string prefix = this.ParserContext.NamespaceManager.LookupPrefix (qname.Namespace, false);
                                if (prefix == null)
                                        return String.Empty;
@@ -474,17 +478,17 @@ namespace Mono.Xml.Schema
                        if (ValidationType == ValidationType.None)      // extra quick check
                                return;
 
-                       XmlSchemaException schemaException = new XmlSchemaException (error, 
+                       ValException schemaException = new ValException (error, 
                                        this, this.BaseURI, null, innerException);
                        HandleError (schemaException, isWarning);
                }
 
-               private void HandleError (XmlSchemaException schemaException)
+               private void HandleError (ValException schemaException)
                {
                        HandleError (schemaException, false);
                }
 
-               private void HandleError (XmlSchemaException schemaException, bool isWarning)
+               private void HandleError (ValException schemaException, bool isWarning)
                {
                        if (ValidationType == ValidationType.None)
                                return;
@@ -501,10 +505,10 @@ namespace Mono.Xml.Schema
 
                private XsElement FindElement (string name, string ns)
                {
-                       return (XsElement) schemas.GlobalElements [new XmlQualifiedName (name, ns)];
+                       return (XsElement) schemas.GlobalElements [new QName (name, ns)];
                }
 
-               private XmlSchemaType FindType (XmlQualifiedName qname)
+               private XmlSchemaType FindType (QName qname)
                {
                        return (XmlSchemaType) schemas.GlobalTypes [qname];
                }
@@ -517,7 +521,7 @@ namespace Mono.Xml.Schema
                        state.CurrentElement = null;
                        Context.EvaluateStartElement (reader.LocalName,
                                reader.NamespaceURI);
-                       if (Context.State == XsdValidationState.Invalid)
+                       if (Context.IsInvalid)
                                HandleError ("Invalid start element: " + reader.NamespaceURI + ":" + reader.LocalName);
 
                        Context.SetElement (state.CurrentElement);
@@ -539,18 +543,27 @@ namespace Mono.Xml.Schema
                        if (xsiNilDepth >= 0 && xsiNilDepth < reader.Depth)
                                HandleError ("Element item appeared, while current element context is nil.");
 
-                       storedCharacters.Append (reader.Value);
+                       if (shouldValidateCharacters)
+                               storedCharacters.Append (reader.Value);
                }
 
                // Utility for missing validation completion related to child items.
-               private void ValidateEndCharacters ()
+               private void ValidateEndSimpleContent ()
+               {
+                       if (shouldValidateCharacters)
+                               ValidateEndSimpleContentCore ();
+                       shouldValidateCharacters = false;
+                       storedCharacters.Length = 0;
+               }
+
+               private void ValidateEndSimpleContentCore ()
                {
                        if (Context.ActualType == null)
                                return;
 
                        string value = storedCharacters.ToString ();
 
-                       if (storedCharacters.Length == 0) {
+                       if (value.Length == 0) {
                                // 3.3.4 Element Locally Valid (Element) 5.1.2
                                if (Context.Element != null) {
                                        if (Context.Element.ValidatedDefaultValue != null)
@@ -569,7 +582,7 @@ namespace Mono.Xml.Schema
                                        switch (ct.ContentType) {
                                        case XmlSchemaContentType.ElementOnly:
                                        case XmlSchemaContentType.Empty:
-                                               if (storedCharacters.Length > 0)
+                                               if (value.Length > 0)
                                                        HandleError ("Character content not allowed.");
                                                break;
                                        }
@@ -583,30 +596,10 @@ namespace Mono.Xml.Schema
                                AssessStringValid (st, dt, value);
                        }
 
-#if !IGNORE_KEYS
-                       // Identity field value
-                       if (currentKeyFieldConsumers != null) {
-                               while (this.currentKeyFieldConsumers.Count > 0) {
-                                       XsdKeyEntryField field = this.currentKeyFieldConsumers [0] as XsdKeyEntryField;
-                                       if (field.Identity != null)
-                                               HandleError ("Two or more identical field was found. Former value is '" + field.Identity + "' .");
-                                       object identity = null; // This means empty value
-                                       if (dt != null) {
-                                               try {
-                                                       identity = dt.ParseValue (value, NameTable, ParserContext.NamespaceManager);
-                                               } catch (Exception ex) { // FIXME: (wishlist) This is bad manner ;-(
-                                                       HandleError ("Identity value is invalid against its data type " + dt.TokenizedType, ex);
-                                               }
-                                       }
-                                       if (identity == null)
-                                               identity = value;
-
-                                       if (!field.SetIdentityField (identity, reader.Depth == xsiNilDepth, dt as XsdAnySimpleType, this))
-                                               HandleError ("Two or more identical key value was found: '" + value + "' .");
-                                       this.currentKeyFieldConsumers.RemoveAt (0);
-                               }
-                       }
-#endif
+#region Key Constraints
+                       if (checkKeyConstraints)
+                               ValidateSimpleContentIdentity (dt, value);
+#endregion
 
                        shouldValidateCharacters = false;
                }
@@ -663,7 +656,7 @@ namespace Mono.Xml.Schema
                                                        else {
                                                                try {
                                                                        AssessStringValid (itemSimpleType, itemSimpleType.Datatype, each);
-                                                               } catch (XmlSchemaException) {
+                                                               } catch (ValException) {
                                                                        continue;
                                                                }
                                                        }
@@ -710,8 +703,7 @@ namespace Mono.Xml.Schema
                private object GetXsiType (string name)
                {
                        object xsiType = null;
-                       XmlQualifiedName typeQName =
-                               XmlQualifiedName.Parse (name, this);
+                       QName typeQName = QName.Parse (name, this);
                        if (typeQName == ComplexType.AnyTypeName)
                                xsiType = ComplexType.AnyType;
                        else if (XmlSchemaUtil.IsBuiltInDatatypeName (typeQName))
@@ -743,7 +735,7 @@ namespace Mono.Xml.Schema
                        if (xsiComplexType != null)
                                try {
                                        xsiComplexType.ValidateTypeDerivationOK (baseType, null, null);
-                               } catch (XmlSchemaException ex) {
+                               } catch (ValException ex) {
 //                                     HandleError ("Locally specified schema complex type derivation failed. " + ex.Message, ex);
                                        HandleError (ex);
                                }
@@ -752,7 +744,7 @@ namespace Mono.Xml.Schema
                                if (xsiSimpleType != null) {
                                        try {
                                                xsiSimpleType.ValidateTypeDerivationOK (baseType, null, null, true);
-                                       } catch (XmlSchemaException ex) {
+                                       } catch (ValException ex) {
 //                                             HandleError ("Locally specified schema simple type derivation failed. " + ex.Message, ex);
                                                HandleError (ex);
                                        }
@@ -825,8 +817,8 @@ namespace Mono.Xml.Schema
                                Context.SetElement (state.CurrentElement);
                        }
                        if (Context.Element != null) {
-                               if (xsiTypeName == null) {
-                                       AssessElementLocallyValidElement (Context.Element, xsiNilValue);        // 1.1.2
+                               if (Context.XsiType == null) {
+                                       AssessElementLocallyValidElement (xsiNilValue); // 1.1.2
                                }
                        } else {
                                switch (state.ProcessContents) {
@@ -838,7 +830,7 @@ namespace Mono.Xml.Schema
                                        if (xsiTypeName == null &&
                                                (schemas.Contains (reader.NamespaceURI) ||
                                                !schemas.MissedSubComponents (reader.NamespaceURI)))
-                                               HandleError ("Element declaration for " + reader.LocalName + " is missing.");
+                                               HandleError ("Element declaration for " + new QName (reader.LocalName, reader.NamespaceURI) + " is missing.");
                                        break;
                                }
                        }
@@ -860,16 +852,20 @@ namespace Mono.Xml.Schema
                        }
                        Context.State = next;
 
-#if !IGNORE_KEYS
-                       AssessStartIdentityConstraints ();
-#endif
+#region Key Constraints
+                       if (checkKeyConstraints) {
+                               ValidateKeySelectors ();
+                               ValidateKeyFields ();
+                       }
+#endregion
 
                }
 
                // 3.3.4 Element Locally Valid (Element)
-               private void AssessElementLocallyValidElement (XsElement element, string xsiNilValue)
+               private void AssessElementLocallyValidElement (string xsiNilValue)
                {
-                       XmlQualifiedName qname = new XmlQualifiedName (reader.LocalName, reader.NamespaceURI);
+                       XsElement element = Context.Element;
+                       QName qname = new QName (reader.LocalName, reader.NamespaceURI);
                        // 1.
                        if (element == null)
                                HandleError ("Element declaration is required for " + qname);
@@ -880,14 +876,14 @@ namespace Mono.Xml.Schema
                        if (!element.ActualIsNillable && xsiNilValue != null)
                                HandleError ("This element declaration is not nillable: " + qname);
                        // 3.2.
-                       // Note that 3.2.1 xsi:nil constraints are to be validated in
+                       // Note that 3.2.1 xsi:nil constraints are to be 
+                       // validated in AssessElementSchemaValidity() and 
+                       // ValidateCharacters().
                        else if (xsiNilValue == "true") {
-                               // AssessElementSchemaValidity() and ValidateCharacters()
-
                                if (element.ValidatedFixedValue != null)
                                        HandleError ("Schema instance nil was specified, where the element declaration for " + qname + "has fixed value constraints.");
                        }
-                       // 4.
+                       // 4. xsi:type (it takes precedence than element type)
                        string xsiType = reader.GetAttribute ("type", XmlSchema.InstanceNamespace);
                        if (xsiType != null) {
                                Context.XsiType = GetXsiType (xsiType);
@@ -965,8 +961,9 @@ namespace Mono.Xml.Schema
                                        case XmlSchema.InstanceNamespace:
                                                continue;
                                        }
-                                       XmlQualifiedName qname = new XmlQualifiedName (reader.LocalName, reader.NamespaceURI);
-                                       XmlSchemaObject attMatch = FindAttributeDeclaration (cType, qname);
+                                       QName qname = new QName (reader.LocalName, reader.NamespaceURI);
+                                       // including 3.10.4 Item Valid (Wildcard)
+                                       XmlSchemaObject attMatch = XmlSchemaUtil.FindAttributeDeclaration (reader.NamespaceURI, schemas, cType, qname);
                                        if (attMatch == null)
                                                HandleError ("Attribute declaration was not found for " + qname);
                                        XsAttribute attdecl = attMatch as XsAttribute;
@@ -1000,47 +997,6 @@ namespace Mono.Xml.Schema
                        // 5. wild IDs was already checked above.
                }
 
-               // Spec 3.10.4 Item Valid (Wildcard)
-               private static bool AttributeWildcardItemValid (XmlSchemaAnyAttribute anyAttr, XmlQualifiedName qname, string ns)
-               {
-                       if (anyAttr.HasValueAny)
-                               return true;
-                       if (anyAttr.HasValueOther && (anyAttr.TargetNamespace == "" || ns != anyAttr.TargetNamespace))
-                               return true;
-                       if (anyAttr.HasValueTargetNamespace && ns == anyAttr.TargetNamespace)
-                               return true;
-                       if (anyAttr.HasValueLocal && ns == "")
-                               return true;
-                       for (int i = 0; i < anyAttr.ResolvedNamespaces.Count; i++)
-                               if (anyAttr.ResolvedNamespaces [i] == ns)
-                                       return true;
-                       return false;
-               }
-
-               private XmlSchemaObject FindAttributeDeclaration (
-                       ComplexType cType,
-                       XmlQualifiedName qname)
-               {
-                       XmlSchemaObject result = cType.AttributeUses [qname];
-                       if (result != null)
-                               return result;
-                       if (cType.AttributeWildcard == null)
-                               return null;
-
-                       if (!AttributeWildcardItemValid (cType.AttributeWildcard, qname, reader.NamespaceURI))
-                               return null;
-
-                       if (cType.AttributeWildcard.ResolvedProcessContents == ContentProc.Skip)
-                               return cType.AttributeWildcard;
-                       XsAttribute attr = schemas.GlobalAttributes [qname] as XsAttribute;
-                       if (attr != null)
-                               return attr;
-                       if (cType.AttributeWildcard.ResolvedProcessContents == ContentProc.Lax)
-                               return cType.AttributeWildcard;
-                       else
-                               return null;
-               }
-
                // 3.2.4 Attribute Locally Valid and 3.4.4
                private void AssessAttributeLocallyValid (XsAttribute attr)
                {
@@ -1063,41 +1019,13 @@ namespace Mono.Xml.Schema
                                        HandleError ("The value of the attribute " + attr.QualifiedName + " does not match with its fixed value.");
                                        parsedValue = dt.ParseValue (attr.ValidatedFixedValue, reader.NameTable, this.ParserContext.NamespaceManager);
                                }
-                               if (this.checkIdentity)
-                                       AssessEachAttributeIdentityConstraint (dt, parsedValue);
-                       }
-               }
-
-               // 3.4.4-5 wild IDs
-               private void AssessEachAttributeIdentityConstraint (
-                       XsDatatype dt, object parsedValue)
-               {
-                       // Validate identity constraints.
-                       string str = parsedValue as string;
-                       switch (dt.TokenizedType) {
-                       case XmlTokenizedType.ID:
-                               if (thisElementId != null)
-                                       HandleError ("ID type attribute was already assigned in the containing element.");
-                               thisElementId = str;
-                               if (idList.Contains (str))
-                                       HandleError ("Duplicate ID value was found.");
-                               else
-                                       idList.Add (str, str);
-                               if (MissingIDReferences.Contains (str))
-                                       MissingIDReferences.Remove (str);
-                               break;
-                       case XmlTokenizedType.IDREF:
-                               if (!idList.Contains (str))
-                                       MissingIDReferences.Add (str);
-                               break;
-                       case XmlTokenizedType.IDREFS:
-                               string [] idrefs = (string []) parsedValue;
-                               for (int i = 0; i < idrefs.Length; i++) {
-                                       string id = idrefs [i];
-                                       if (!idList.Contains (id))
-                                               MissingIDReferences.Add (id);
+#region ID Constraints
+                               if (this.checkIdentity) {
+                                       string error = idManager.AssessEachAttributeIdentityConstraint (dt, parsedValue, ((QName) elementQNameStack [elementQNameStack.Count - 1]).Name);
+                                       if (error != null)
+                                               HandleError (error);
                                }
-                               break;
+#endregion
                        }
                }
 
@@ -1112,31 +1040,40 @@ namespace Mono.Xml.Schema
                {
                        ValidateEndElementParticle ();  // validate against childrens' state.
 
-                       if (shouldValidateCharacters) {
-                               ValidateEndCharacters ();
-                               shouldValidateCharacters = false;
-                       }
+                       ValidateEndSimpleContent ();
 
-#if !IGNORE_KEYS
                        // 3.3.4 Assess ElementLocallyValidElement 5: value constraints.
                        // 3.3.4 Assess ElementLocallyValidType 3.1.3. = StringValid(3.14.4)
-                       // => ValidateEndCharacters().
+                       // => ValidateEndSimpleContent().
+
+#region Key Constraints
+                       if (checkKeyConstraints)
+                               ValidateEndElementKeyConstraints ();
+#endregion
 
+                       // Reset xsi:nil, if required.
+                       if (xsiNilDepth == reader.Depth)
+                               xsiNilDepth = -1;
+               }
+
+#region Key Constraints
+               private void ValidateEndElementKeyConstraints ()
+               {
                        // Reset Identity constraints.
                        for (int i = 0; i < keyTables.Count; i++) {
-                               XsdKeyTable keyTable = this.keyTables [i] as XsdKeyTable;
-                               if (keyTable.StartDepth == reader.Depth) {
-                                       EndIdentityValidation (keyTable);
+                               XsdKeyTable seq = this.keyTables [i] as XsdKeyTable;
+                               if (seq.StartDepth == reader.Depth) {
+                                       EndIdentityValidation (seq);
                                } else {
-                                       for (int k = 0; k < keyTable.Entries.Count; k++) {
-                                               XsdKeyEntry entry = keyTable.Entries [k] as XsdKeyEntry;
+                                       for (int k = 0; k < seq.Entries.Count; k++) {
+                                               XsdKeyEntry entry = seq.Entries [k] as XsdKeyEntry;
                                                // Remove finished (maybe key not found) entries.
                                                if (entry.StartDepth == reader.Depth) {
                                                        if (entry.KeyFound)
-                                                               keyTable.FinishedEntries.Add (entry);
-                                                       else if (entry.KeySequence.SourceSchemaIdentity is XmlSchemaKey)
+                                                               seq.FinishedEntries.Add (entry);
+                                                       else if (seq.SourceSchemaIdentity is XmlSchemaKey)
                                                                HandleError ("Key sequence is missing.");
-                                                       keyTable.Entries.RemoveAt (k);
+                                                       seq.Entries.RemoveAt (k);
                                                        k--;
                                                }
                                                // Pop validated key depth to find two or more fields.
@@ -1153,22 +1090,16 @@ namespace Mono.Xml.Schema
                                }
                        }
                        for (int i = 0; i < keyTables.Count; i++) {
-                               XsdKeyTable keyseq = this.keyTables [i] as XsdKeyTable;
-                               if (keyseq.StartDepth == reader.Depth) {
+                               XsdKeyTable seq = this.keyTables [i] as XsdKeyTable;
+                               if (seq.StartDepth == reader.Depth) {
                                        keyTables.RemoveAt (i);
                                        i--;
                                }
                        }
-#endif
-
-                       // Reset xsi:nil, if required.
-                       if (xsiNilDepth == reader.Depth)
-                               xsiNilDepth = -1;
                }
 
-#if !IGNORE_KEYS
                // 3.11.4 Identity Constraint Satisfied
-               private void AssessStartIdentityConstraints ()
+               private void ValidateKeySelectors ()
                {
                        if (tmpKeyrefPool != null)
                                tmpKeyrefPool.Clear ();
@@ -1188,83 +1119,142 @@ namespace Mono.Xml.Schema
                        // (b) Evaluate current key sequences.
                        for (int i = 0; i < keyTables.Count; i++) {
                                XsdKeyTable seq  = (XsdKeyTable) keyTables [i];
-                               if (seq.SelectorMatches (this.elementQNameStack, reader) != null) {
+                               if (seq.SelectorMatches (this.elementQNameStack, reader.Depth) != null) {
                                        // creates and registers new entry.
-                                       XsdKeyEntry entry = new XsdKeyEntry (seq, reader);
+                                       XsdKeyEntry entry = new XsdKeyEntry (seq, reader.Depth, readerLineInfo);
                                        seq.Entries.Add (entry);
                                }
                        }
+               }
 
+               private void ValidateKeyFields ()
+               {
                        // (c) Evaluate field paths.
                        for (int i = 0; i < keyTables.Count; i++) {
                                XsdKeyTable seq  = (XsdKeyTable) keyTables [i];
                                // If possible, create new field entry candidates.
                                for (int j = 0; j < seq.Entries.Count; j++) {
-                                       XsdKeyEntry entry = seq.Entries [j] as XsdKeyEntry;
                                        try {
-                                               entry.FieldMatches (this.elementQNameStack, this);
-                                       } catch (Exception ex) { // FIXME: (wishlist) It is bad manner ;-(
-                                               HandleError ("Identity field value is invalid against its data type.", ex);
+                                               ProcessKeyEntry (seq.Entries [j]);
+                                       } catch (ValException ex) {
+                                               HandleError (ex);
                                        }
                                }
                        }
                }
 
+               private void ProcessKeyEntry (XsdKeyEntry entry)
+               {
+                       bool isNil = XsiNilDepth == Depth;
+                       entry.ProcessMatch (false, elementQNameStack, this, NameTable, BaseURI, SchemaType, ParserContext.NamespaceManager, readerLineInfo, Depth, null, null, null, isNil, CurrentKeyFieldConsumers);
+                       if (MoveToFirstAttribute ()) {
+                               try {
+                                       do {
+                                               switch (NamespaceURI) {
+                                               case XmlNamespaceManager.XmlnsXmlns:
+                                               case XmlSchema.InstanceNamespace:
+                                                       continue;
+                                               }
+                                               entry.ProcessMatch (true, elementQNameStack, this, NameTable, BaseURI, SchemaType, ParserContext.NamespaceManager, readerLineInfo, Depth, LocalName, NamespaceURI, Value, false, CurrentKeyFieldConsumers);
+                                       } while (MoveToNextAttribute ());
+                               } finally {
+                                       MoveToElement ();
+                               }
+                       }
+               }
+
                private XsdKeyTable CreateNewKeyTable (XmlSchemaIdentityConstraint ident)
                {
-                       XsdKeyTable seq = new XsdKeyTable (ident, this);
+                       XsdKeyTable seq = new XsdKeyTable (ident);
                        seq.StartDepth = reader.Depth;
                        this.keyTables.Add (seq);
                        return seq;
                }
 
+               private void ValidateSimpleContentIdentity (
+                       XmlSchemaDatatype dt, string value)
+               {
+                       // Identity field value
+                       if (currentKeyFieldConsumers != null) {
+                               while (this.currentKeyFieldConsumers.Count > 0) {
+                                       XsdKeyEntryField field = this.currentKeyFieldConsumers [0] as XsdKeyEntryField;
+                                       if (field.Identity != null)
+                                               HandleError ("Two or more identical field was found. Former value is '" + field.Identity + "' .");
+                                       object identity = null; // This means empty value
+                                       if (dt != null) {
+                                               try {
+                                                       identity = dt.ParseValue (value, NameTable, ParserContext.NamespaceManager);
+                                               } catch (Exception ex) { // FIXME: (wishlist) This is bad manner ;-(
+                                                       HandleError ("Identity value is invalid against its data type " + dt.TokenizedType, ex);
+                                               }
+                                       }
+                                       if (identity == null)
+                                               identity = value;
+
+                                       if (!field.SetIdentityField (identity, reader.Depth == xsiNilDepth, dt as XsdAnySimpleType, this.Depth, readerLineInfo))
+                                               HandleError ("Two or more identical key value was found: '" + value + "' .");
+                                       this.currentKeyFieldConsumers.RemoveAt (0);
+                               }
+                       }
+               }
+
                private void EndIdentityValidation (XsdKeyTable seq)
                {
-                       ArrayList errors = new ArrayList ();
+                       ArrayList errors = null;
                        for (int i = 0; i < seq.Entries.Count; i++) {
                                XsdKeyEntry entry = (XsdKeyEntry) seq.Entries [i];
                                if (entry.KeyFound)
                                        continue;
-                               if (seq.SourceSchemaIdentity is XmlSchemaKey)
+                               if (seq.SourceSchemaIdentity is XmlSchemaKey) {
+                                       if (errors == null)
+                                               errors = new ArrayList ();
                                        errors.Add ("line " + entry.SelectorLineNumber + "position " + entry.SelectorLinePosition);
+                               }
                        }
-                       if (errors.Count > 0)
+                       if (errors != null)
                                HandleError ("Invalid identity constraints were found. Key was not found. "
                                        + String.Join (", ", errors.ToArray (typeof (string)) as string []));
 
-                       errors.Clear ();
-                       // Find reference target
+                       // If it is keyref, then find reference target
                        XmlSchemaKeyref xsdKeyref = seq.SourceSchemaIdentity as XmlSchemaKeyref;
-                       if (xsdKeyref != null) {
-                               for (int i = this.keyTables.Count - 1; i >= 0; i--) {
-                                       XsdKeyTable target = this.keyTables [i] as XsdKeyTable;
-                                       if (target.SourceSchemaIdentity == xsdKeyref.Target) {
-                                               seq.ReferencedKey = target;
-                                               for (int j = 0; j < seq.FinishedEntries.Count; j++) {
-                                                       XsdKeyEntry entry = (XsdKeyEntry) seq.FinishedEntries [j];
-                                                       for (int k = 0; k < target.FinishedEntries.Count; k++) {
-                                                               XsdKeyEntry targetEntry = (XsdKeyEntry) target.FinishedEntries [k];
-                                                               if (entry.CompareIdentity (targetEntry)) {
-                                                                       entry.KeyRefFound = true;
-                                                                       break;
-                                                               }
-                                                       }
+                       if (xsdKeyref != null)
+                               EndKeyrefValidation (seq, xsdKeyref.Target);
+               }
+
+               private void EndKeyrefValidation (XsdKeyTable seq, XmlSchemaIdentityConstraint targetIdent)
+               {
+                       for (int i = this.keyTables.Count - 1; i >= 0; i--) {
+                               XsdKeyTable target = this.keyTables [i] as XsdKeyTable;
+                               if (target.SourceSchemaIdentity != targetIdent)
+                                       continue;
+                               seq.ReferencedKey = target;
+                               for (int j = 0; j < seq.FinishedEntries.Count; j++) {
+                                       XsdKeyEntry entry = (XsdKeyEntry) seq.FinishedEntries [j];
+                                       for (int k = 0; k < target.FinishedEntries.Count; k++) {
+                                               XsdKeyEntry targetEntry = (XsdKeyEntry) target.FinishedEntries [k];
+                                               if (entry.CompareIdentity (targetEntry)) {
+                                                       entry.KeyRefFound = true;
+                                                       break;
                                                }
                                        }
                                }
-                               if (seq.ReferencedKey == null)
-                                       HandleError ("Target key was not found.");
-                               for (int i = 0; i < seq.FinishedEntries.Count; i++) {
-                                       XsdKeyEntry entry = (XsdKeyEntry) seq.FinishedEntries [i];
-                                       if (!entry.KeyRefFound)
-                                               errors.Add (" line " + entry.SelectorLineNumber + ", position " + entry.SelectorLinePosition);
+                       }
+                       if (seq.ReferencedKey == null)
+                               HandleError ("Target key was not found.");
+                       ArrayList errors = null;
+                       for (int i = 0; i < seq.FinishedEntries.Count; i++) {
+                               XsdKeyEntry entry = (XsdKeyEntry) seq.FinishedEntries [i];
+                               if (!entry.KeyRefFound) {
+                                       if (errors == null)
+                                               errors = new ArrayList ();
+                                       errors.Add (" line " + entry.SelectorLineNumber + ", position " + entry.SelectorLinePosition);
                                }
-                               if (errors.Count > 0)
-                                       HandleError ("Invalid identity constraints were found. Referenced key was not found: "
-                                               + String.Join (" / ", errors.ToArray (typeof (string)) as string []));
                        }
+                       if (errors != null)
+                               HandleError ("Invalid identity constraints were found. Referenced key was not found: "
+                                       + String.Join (" / ", errors.ToArray (typeof (string)) as string []));
                }
-#endif
+#endregion
 
                // Overrided Methods
 
@@ -1302,19 +1292,19 @@ namespace Mono.Xml.Schema
                        if (value != null)
                                return value;
 
-                       XmlQualifiedName qname = SplitQName (name);
+                       QName qname = SplitQName (name);
                        return GetDefaultAttribute (qname.Name, qname.Namespace);
                }
 
-               private XmlQualifiedName SplitQName (string name)
+               private QName SplitQName (string name)
                {
                        if (!XmlChar.IsName (name))
                                throw new ArgumentException ("Invalid name was specified.", "name");
 
                        Exception ex = null;
-                       XmlQualifiedName qname = XmlSchemaUtil.ToQName (reader, name, out ex);
+                       QName qname = XmlSchemaUtil.ToQName (reader, name, out ex);
                        if (ex != null)
-                               return XmlQualifiedName.Empty;
+                               return QName.Empty;
                        else
                                return qname;
                }
@@ -1356,7 +1346,7 @@ namespace Mono.Xml.Schema
                        return -1;
                }
 
-               bool IXmlLineInfo.HasLineInfo ()
+               public bool HasLineInfo ()
                {
                        return readerLineInfo != null && readerLineInfo.HasLineInfo ();
                }
@@ -1384,7 +1374,7 @@ namespace Mono.Xml.Schema
                                return;
                        }
 
-                       attrQName = null;
+                       currentAttrType = null;
                        if (i < reader.AttributeCount) {
                                reader.MoveToAttribute (i);
                                this.currentDefaultAttribute = -1;
@@ -1407,7 +1397,7 @@ namespace Mono.Xml.Schema
                                return reader.MoveToAttribute (name);
                        }
 
-                       attrQName = null;
+                       currentAttrType = null;
                        bool b = reader.MoveToAttribute (name);
                        if (b) {
                                this.currentDefaultAttribute = -1;
@@ -1426,7 +1416,7 @@ namespace Mono.Xml.Schema
                                return reader.MoveToAttribute (localName, ns);
                        }
 
-                       attrQName = null;
+                       currentAttrType = null;
                        bool b = reader.MoveToAttribute (localName, ns);
                        if (b) {
                                this.currentDefaultAttribute = -1;
@@ -1451,7 +1441,7 @@ namespace Mono.Xml.Schema
                {
                        currentDefaultAttribute = -1;
                        defaultAttributeConsumed = false;
-                       attrQName = null;
+                       currentAttrType = null;
                        return reader.MoveToElement ();
                }
 
@@ -1463,7 +1453,7 @@ namespace Mono.Xml.Schema
                                return reader.MoveToFirstAttribute ();
                        }
 
-                       attrQName = null;
+                       currentAttrType = null;
                        if (reader.AttributeCount > 0) {
                                bool b = reader.MoveToFirstAttribute ();
                                if (b) {
@@ -1490,7 +1480,7 @@ namespace Mono.Xml.Schema
                                return reader.MoveToNextAttribute ();
                        }
 
-                       attrQName = null;
+                       currentAttrType = null;
                        if (currentDefaultAttribute >= 0) {
                                if (defaultAttributes.Length == currentDefaultAttribute + 1)
                                        return false;
@@ -1515,8 +1505,28 @@ namespace Mono.Xml.Schema
                                return false;
                }
 
+               private XmlSchema ReadExternalSchema (string uri)
+               {
+                       Uri absUri = resolver.ResolveUri ((BaseURI != "" ? new Uri (BaseURI) : null), uri);
+                       string absUriString = absUri != null ? absUri.ToString () : String.Empty;
+                       XmlTextReader xtr = null;
+                       try {
+                               xtr = new XmlTextReader (absUriString,
+                                       (Stream) resolver.GetEntity (
+                                               absUri, null, typeof (Stream)),
+                                       NameTable);
+                               return XmlSchema.Read (
+                                       xtr, ValidationEventHandler);
+                       } finally {
+                               if (xtr != null)
+                                       xtr.Close ();
+                       }
+               }
+
                private void ExamineAdditionalSchema ()
                {
+                       if (resolver == null)
+                               return;
                        XmlSchema schema = null;
                        string schemaLocation = reader.GetAttribute ("schemaLocation", XmlSchema.InstanceNamespace);
                        bool schemaAdded = false;
@@ -1532,18 +1542,11 @@ namespace Mono.Xml.Schema
                                if (tmp.Length % 2 != 0)
                                        HandleError ("Invalid schemaLocation attribute format.");
                                for (int i = 0; i < tmp.Length; i += 2) {
-                                       Uri absUri = null;
-                                       XmlTextReader xtr = null;
                                        try {
-                                               absUri = new Uri ((this.BaseURI != "" ? new Uri (BaseURI) : null), tmp [i + 1]);
-                                               xtr = new XmlTextReader (absUri.ToString (), NameTable);
-                                               schema = XmlSchema.Read (xtr, null);
+                                               schema = ReadExternalSchema (tmp [i + 1]);
                                        } catch (Exception) { // FIXME: (wishlist) It is bad manner ;-(
-                                               HandleError ("Could not resolve schema location URI: " + absUri, null, true);
+                                               HandleError ("Could not resolve schema location URI: " + tmp [i + 1], null, true);
                                                continue;
-                                       } finally {
-                                               if (xtr != null)
-                                                       xtr.Close ();
                                        }
                                        if (schema.TargetNamespace == null)
                                                schema.TargetNamespace = tmp [i];
@@ -1560,17 +1563,10 @@ namespace Mono.Xml.Schema
                        schema = null;
                        string noNsSchemaLocation = reader.GetAttribute ("noNamespaceSchemaLocation", XmlSchema.InstanceNamespace);
                        if (noNsSchemaLocation != null) {
-                               Uri absUri = null;
-                               XmlTextReader xtr = null;
                                try {
-                                       absUri = new Uri ((this.BaseURI != "" ? new Uri (BaseURI) : null), noNsSchemaLocation);
-                                       xtr = new XmlTextReader (absUri.ToString (), NameTable);
-                                       schema = XmlSchema.Read (xtr, null);
+                                       schema = ReadExternalSchema (noNsSchemaLocation);
                                } catch (Exception) { // FIXME: (wishlist) It is bad manner ;-(
-                                       HandleError ("Could not resolve schema location URI: " + absUri, null, true);
-                               } finally {
-                                       if (xtr != null)
-                                               xtr.Close ();
+                                       HandleError ("Could not resolve schema location URI: " + noNsSchemaLocation, null, true);
                                }
                                if (schema != null && schema.TargetNamespace != null)
                                        HandleError ("Specified schema has different target namespace.");
@@ -1586,28 +1582,24 @@ namespace Mono.Xml.Schema
                                schemas.Compile ();
                }
 
-               private bool HasMissingIDReferences ()
-               {
-                       return missingIDReferences != null
-                               && missingIDReferences.Count > 0;
-               }
-
                public override bool Read ()
                {
                        currentDefaultAttribute = -1;
                        defaultAttributeConsumed = false;
-                       attrQName = null;
+                       currentAttrType = null;
+#region ID Constraints
                        if (this.checkIdentity)
-                               thisElementId = null;
+                               idManager.OnStartElement ();
+#endregion
                        defaultAttributes = emptyAttributeArray;
 
                        bool result = reader.Read ();
+#region ID Constraints
                        // 3.3.4 ElementLocallyValidElement 7 = Root Valid.
                        if (!result && this.checkIdentity &&
-                               HasMissingIDReferences ())
-                               HandleError ("There are missing ID references: " +
-                                       String.Join (" ",
-                                       this.missingIDReferences.ToArray (typeof (string)) as string []));
+                               idManager.HasMissingIDReferences ())
+                               HandleError ("There are missing ID references: " + idManager.GetMissingIDString ());
+#endregion
 
                        // FIXME: schemaLocation could be specified 
                        // at any Depth.
@@ -1621,18 +1613,15 @@ namespace Mono.Xml.Schema
 
                        switch (reader.NodeType) {
                        case XmlNodeType.Element:
-#if !IGNORE_KEYS
-                               this.elementQNameStack.Add (new XmlQualifiedName (reader.LocalName, reader.NamespaceURI));
-#endif
+#region Key Constraints
+                               if (checkKeyConstraints)
+                                       this.elementQNameStack.Add (new QName (reader.LocalName, reader.NamespaceURI));
+#endregion
 
                                // If there is no schema information, then no validation is performed.
                                if (skipValidationDepth < 0 || reader.Depth <= skipValidationDepth) {
-                                       if (shouldValidateCharacters) {
-                                               ValidateEndCharacters ();
-                                               shouldValidateCharacters = false;
-                                       }
+                                       ValidateEndSimpleContent ();
                                        AssessStartElementSchemaValidity ();
-                                       storedCharacters.Length = 0;
                                }
 
                                if (reader.IsEmptyElement)
@@ -1646,13 +1635,14 @@ namespace Mono.Xml.Schema
                                else if (skipValidationDepth < 0 || reader.Depth <= skipValidationDepth)
                                        AssessEndElementSchemaValidity ();
 
-                               storedCharacters.Length = 0;
-                               elementQNameStack.RemoveAt (elementQNameStack.Count - 1);
+                               if (checkKeyConstraints)
+                                       elementQNameStack.RemoveAt (elementQNameStack.Count - 1);
                                break;
 
                        case XmlNodeType.CDATA:
                        case XmlNodeType.SignificantWhitespace:
                        case XmlNodeType.Text:
+                               // FIXME: does this check make sense?
                                ComplexType ct = Context.ActualType as ComplexType;
                                if (ct != null && storedCharacters.Length > 0) {
                                        switch (ct.ContentType) {
@@ -1721,8 +1711,8 @@ namespace Mono.Xml.Schema
 
                // Some of them might be missing (See the spec section 5.3, and also 3.3.4).
                public XsElement Element;
-               public XsdValidationState State;
                public object XsiType; // xsi:type
+               internal XsdValidationState State;
 
                // Note that it represents current element's type.
                public object ActualType {
@@ -1734,6 +1724,25 @@ namespace Mono.Xml.Schema
                        }
                }
 
+#if NET_2_0
+               public XmlSchemaType ActualSchemaType {
+                       get {
+                               object at = ActualType;
+                               if (at == null)
+                                       return null;
+                               XmlSchemaType st = at as XmlSchemaType;
+                               if (st == null)
+                                       st = XmlSchemaType.GetBuiltInSimpleType (
+                                       ((XmlSchemaDatatype) at).TypeCode);
+                               return st;
+                       }
+               }
+#endif
+
+               public bool IsInvalid {
+                       get { return State == XsdValidationState.Invalid; }
+               }
+
                public object Clone ()
                {
                        return MemberwiseClone ();
@@ -1755,4 +1764,81 @@ namespace Mono.Xml.Schema
                        Element = element;
                }
        }
+
+       internal class XsdIDManager
+       {
+               public XsdIDManager ()
+               {
+               }
+
+               Hashtable idList = new Hashtable ();
+               ArrayList missingIDReferences;
+               string thisElementId;
+
+               private ArrayList MissingIDReferences {
+                       get {
+                               if (missingIDReferences == null)
+                                       missingIDReferences = new ArrayList ();
+                               return missingIDReferences;
+                       }
+               }
+
+               public void OnStartElement ()
+               {
+                       thisElementId = null;
+               }
+
+               // 3.4.4-5 wild IDs
+               public string AssessEachAttributeIdentityConstraint (
+                       XsDatatype dt, object parsedValue, string elementName)
+               {
+                       // Validate identity constraints.
+                       string str = parsedValue as string;
+                       switch (dt.TokenizedType) {
+                       case XmlTokenizedType.ID:
+                               if (thisElementId != null)
+                                       return "ID type attribute was already assigned in the containing element.";
+                               else
+                                       thisElementId = str;
+                               if (idList.ContainsKey (str))
+                                       return "Duplicate ID value was found.";
+                               else
+                                       idList.Add (str, elementName);
+                               if (MissingIDReferences.Contains (str))
+                                       MissingIDReferences.Remove (str);
+                               break;
+                       case XmlTokenizedType.IDREF:
+                               if (!idList.Contains (str))
+                                       MissingIDReferences.Add (str);
+                               break;
+                       case XmlTokenizedType.IDREFS:
+                               string [] idrefs = (string []) parsedValue;
+                               for (int i = 0; i < idrefs.Length; i++) {
+                                       string id = idrefs [i];
+                                       if (!idList.Contains (id))
+                                               MissingIDReferences.Add (id);
+                               }
+                               break;
+                       }
+                       return null;
+               }
+
+               public object FindID (string name)
+               {
+                       return idList [name];
+               }
+
+               public bool HasMissingIDReferences ()
+               {
+                       return missingIDReferences != null
+                               && missingIDReferences.Count > 0;
+               }
+
+               public string GetMissingIDString ()
+               {
+                       return String.Join (" ",
+                               MissingIDReferences.ToArray (typeof (string))
+                                       as string []);
+               }
+       }
 }