svn path=/branches/mono-1-1-9/mcs/; revision=51207
[mono.git] / mcs / class / System.XML / Mono.Xml.Schema / XsdValidatingReader.cs
index 899f2b4186556eecc9a62129f55c0b223dd9eac1..4355366e729abcd798ee4662d23eec983cd670ad 100644 (file)
@@ -29,6 +29,9 @@
 //
 using System;
 using System.Collections;
+#if NET_2_0
+using System.Collections.Generic;
+#endif
 using System.Collections.Specialized;
 using System.IO;
 using System.Text;
@@ -36,6 +39,13 @@ 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;
@@ -63,9 +73,7 @@ namespace Mono.Xml.Schema
 
 #region ID Constraints
                bool checkIdentity = true;
-               Hashtable idList = new Hashtable ();
-               ArrayList missingIDReferences;
-               string thisElementId;
+               XsdIDManager idManager = new XsdIDManager ();
 #endregion
 
 #region Key Constraints
@@ -73,8 +81,8 @@ namespace Mono.Xml.Schema
                ArrayList keyTables = new ArrayList ();
                ArrayList currentKeyFieldConsumers;
                ArrayList tmpKeyrefPool;
-               ArrayList elementQNameStack = new ArrayList ();
 #endregion
+               ArrayList elementQNameStack = new ArrayList ();
 
                XsdParticleStateManager state = new XsdParticleStateManager ();
 
@@ -117,14 +125,6 @@ namespace Mono.Xml.Schema
                }
 #endregion
 
-               private ArrayList MissingIDReferences {
-                       get {
-                               if (missingIDReferences == null)
-                                       missingIDReferences = new ArrayList ();
-                               return missingIDReferences;
-                       }
-               }
-
                // Public Non-overrides
 
                public int XsiNilDepth {
@@ -168,7 +168,7 @@ namespace Mono.Xml.Schema
                                        if (currentAttrType == null) {
                                                ComplexType ct = Context.ActualType as ComplexType;
                                                if (ct != null) {
-                                                       XsAttribute attdef = ct.AttributeUses [new XmlQualifiedName (LocalName, NamespaceURI)] as XsAttribute;
+                                                       XsAttribute attdef = ct.AttributeUses [new QName (LocalName, NamespaceURI)] as XsAttribute;
                                                        if (attdef != null)
                                                                currentAttrType = attdef.AttributeType;
                                                        return currentAttrType;
@@ -195,7 +195,12 @@ namespace Mono.Xml.Schema
                        }
                }
 
-               IDictionary IXmlNamespaceResolver.GetNamespacesInScope (XmlNamespaceScope scope)
+#if NET_2_0
+               IDictionary<string, string> 
+#else
+               IDictionary
+#endif
+               IXmlNamespaceResolver.GetNamespacesInScope (XmlNamespaceScope scope)
                {
                        IXmlNamespaceResolver resolver = reader as IXmlNamespaceResolver;
                        if (resolver == null)
@@ -204,20 +209,16 @@ namespace Mono.Xml.Schema
                }
 
                string IXmlNamespaceResolver.LookupPrefix (string ns)
-               {
-                       return ((IXmlNamespaceResolver) this).LookupPrefix (ns, false);
-               }
-
-               string IXmlNamespaceResolver.LookupPrefix (string ns, bool atomizedNames)
                {
                        IXmlNamespaceResolver resolver = reader as IXmlNamespaceResolver;
                        if (resolver == null)
                                throw new NotSupportedException ("The input XmlReader does not implement IXmlNamespaceResolver and thus this validating reader cannot execute namespace prefix lookup.");
-                       return resolver.LookupPrefix (ns, atomizedNames);
+                       return resolver.LookupPrefix (ns);
                }
 
                // It is used only for independent XmlReader use, not for XmlValidatingReader.
 #if NET_2_0
+               [Obsolete]
                public override object ReadTypedValue ()
 #else
                public object ReadTypedValue ()
@@ -230,44 +231,6 @@ namespace Mono.Xml.Schema
                        return o;
                }
                
-               private object ReadTypedValueCore ()
-               {
-                       XsDatatype dt = SchemaType as XsDatatype;
-                       SimpleType st = SchemaType as SimpleType;
-                       if (st != null)
-                               dt = st.Datatype;
-                       if (dt == null)
-                               return null;
-
-                       switch (NodeType) {
-                       case XmlNodeType.Element:
-                               if (IsEmptyElement)
-                                       return null;
-
-                               storedCharacters.Length = 0;
-                               bool loop = true;
-                               do {
-                                       Read ();
-                                       switch (NodeType) {
-                                       case XmlNodeType.SignificantWhitespace:
-                                       case XmlNodeType.Text:
-                                       case XmlNodeType.CDATA:
-                                               storedCharacters.Append (Value);
-                                               break;
-                                       case XmlNodeType.Comment:
-                                               break;
-                                       default:
-                                               loop = false;
-                                               break;
-                                       }
-                               } while (loop && !EOF && ReadState == ReadState.Interactive);
-                               return dt.ParseValue (storedCharacters.ToString (), NameTable, ParserContext.NamespaceManager);
-                       case XmlNodeType.Attribute:
-                               return dt.ParseValue (Value, NameTable, ParserContext.NamespaceManager);
-                       }
-                       return null;
-               }
-
                // Public Overriden Properties
 
                public override int AttributeCount {
@@ -337,11 +300,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; }
                }
 
@@ -362,7 +325,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;
@@ -405,7 +368,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;
@@ -480,17 +443,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;
@@ -507,10 +470,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];
                }
@@ -550,15 +513,15 @@ namespace Mono.Xml.Schema
                }
 
                // Utility for missing validation completion related to child items.
-               private void ValidateEndCharacters ()
+               private void ValidateEndSimpleContent ()
                {
                        if (shouldValidateCharacters)
-                               ValidateEndCharactersCore ();
+                               ValidateEndSimpleContentCore ();
                        shouldValidateCharacters = false;
                        storedCharacters.Length = 0;
                }
 
-               private void ValidateEndCharactersCore ()
+               private void ValidateEndSimpleContentCore ()
                {
                        if (Context.ActualType == null)
                                return;
@@ -606,35 +569,6 @@ namespace Mono.Xml.Schema
                        shouldValidateCharacters = false;
                }
 
-#region Key Constraints
-               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, (IXmlLineInfo) this))
-                                               HandleError ("Two or more identical key value was found: '" + value + "' .");
-                                       this.currentKeyFieldConsumers.RemoveAt (0);
-                               }
-                       }
-               }
-#endregion
-
                // 3.14.4 String Valid 
                private void AssessStringValid (SimpleType st,
                        XsDatatype dt, string value)
@@ -687,7 +621,7 @@ namespace Mono.Xml.Schema
                                                        else {
                                                                try {
                                                                        AssessStringValid (itemSimpleType, itemSimpleType.Datatype, each);
-                                                               } catch (XmlSchemaException) {
+                                                               } catch (ValException) {
                                                                        continue;
                                                                }
                                                        }
@@ -734,8 +668,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))
@@ -767,7 +700,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);
                                }
@@ -776,7 +709,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);
                                        }
@@ -849,8 +782,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) {
@@ -862,7 +795,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;
                                }
                        }
@@ -885,16 +818,19 @@ namespace Mono.Xml.Schema
                        Context.State = next;
 
 #region Key Constraints
-                       if (checkKeyConstraints)
-                               AssessStartIdentityConstraints ();
+                       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);
@@ -905,14 +841,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);
@@ -990,8 +926,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;
@@ -1025,47 +962,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)
                {
@@ -1089,42 +985,12 @@ namespace Mono.Xml.Schema
                                        parsedValue = dt.ParseValue (attr.ValidatedFixedValue, reader.NameTable, this.ParserContext.NamespaceManager);
                                }
 #region ID Constraints
-                               if (this.checkIdentity)
-                                       AssessEachAttributeIdentityConstraint (dt, parsedValue);
-#endregion
-                       }
-               }
-
-               // 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);
+                               if (this.checkIdentity) {
+                                       string error = idManager.AssessEachAttributeIdentityConstraint (dt, parsedValue, ((QName) elementQNameStack [elementQNameStack.Count - 1]).Name);
+                                       if (error != null)
+                                               HandleError (error);
                                }
-                               break;
+#endregion
                        }
                }
 
@@ -1139,11 +1005,11 @@ namespace Mono.Xml.Schema
                {
                        ValidateEndElementParticle ();  // validate against childrens' state.
 
-                       ValidateEndCharacters ();
+                       ValidateEndSimpleContent ();
 
                        // 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)
@@ -1170,7 +1036,7 @@ namespace Mono.Xml.Schema
                                                if (entry.StartDepth == reader.Depth) {
                                                        if (entry.KeyFound)
                                                                seq.FinishedEntries.Add (entry);
-                                                       else if (entry.KeySequence.SourceSchemaIdentity is XmlSchemaKey)
+                                                       else if (seq.SourceSchemaIdentity is XmlSchemaKey)
                                                                HandleError ("Key sequence is missing.");
                                                        seq.Entries.RemoveAt (k);
                                                        k--;
@@ -1198,7 +1064,7 @@ namespace Mono.Xml.Schema
                }
 
                // 3.11.4 Identity Constraint Satisfied
-               private void AssessStartIdentityConstraints ()
+               private void ValidateKeySelectors ()
                {
                        if (tmpKeyrefPool != null)
                                tmpKeyrefPool.Clear ();
@@ -1218,81 +1084,140 @@ 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.Depth, reader as IXmlLineInfo);
+                                       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];
                                        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 []));
                }
 #endregion
 
@@ -1332,19 +1257,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;
                }
@@ -1386,7 +1311,7 @@ namespace Mono.Xml.Schema
                        return -1;
                }
 
-               bool IXmlLineInfo.HasLineInfo ()
+               public bool HasLineInfo ()
                {
                        return readerLineInfo != null && readerLineInfo.HasLineInfo ();
                }
@@ -1396,15 +1321,6 @@ namespace Mono.Xml.Schema
                        return reader.LookupNamespace (prefix);
                }
 
-               string IXmlNamespaceResolver.LookupNamespace (string prefix, bool atomizedNames)
-               {
-                       IXmlNamespaceResolver res = reader as IXmlNamespaceResolver;
-                       if (res != null)
-                               return res.LookupNamespace (prefix, atomizedNames);
-                       else
-                               return reader.LookupNamespace (prefix);
-               }
-
                public override void MoveToAttribute (int i)
                {
                        switch (reader.NodeType) {
@@ -1545,6 +1461,24 @@ 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)
@@ -1558,27 +1492,21 @@ namespace Mono.Xml.Schema
                                        schemaLocation = XsDatatype.FromName ("token", XmlSchema.Namespace).Normalize (schemaLocation);
                                        tmp = schemaLocation.Split (XmlChar.WhitespaceChars);
                                } catch (Exception ex) {
-                                       HandleError ("Invalid schemaLocation attribute format.", ex, true);
+                                       if (schemas.Count == 0)
+                                               HandleError ("Invalid schemaLocation attribute format.", ex, true);
                                        tmp = new string [0];
                                }
                                if (tmp.Length % 2 != 0)
-                                       HandleError ("Invalid schemaLocation attribute format.");
+                                       if (schemas.Count == 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 (),
-                                                       (Stream) resolver.GetEntity (absUri, null, typeof (Stream)),
-                                                       NameTable);
-                                               schema = XmlSchema.Read (xtr, ValidationEventHandler);
+                                               schema = ReadExternalSchema (tmp [i + 1]);
                                        } catch (Exception) { // FIXME: (wishlist) It is bad manner ;-(
-                                               HandleError ("Could not resolve schema location URI: " + absUri, null, true);
+                                               if (!schemas.Contains (tmp [i]))
+                                                       HandleError (String.Format ("Could not resolve schema location URI: {0}",
+                                                               i + 1 < tmp.Length ? tmp [i + 1] : String.Empty), null, true);
                                                continue;
-                                       } finally {
-                                               if (xtr != null)
-                                                       xtr.Close ();
                                        }
                                        if (schema.TargetNamespace == null)
                                                schema.TargetNamespace = tmp [i];
@@ -1595,20 +1523,11 @@ 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 (),
-                                               (Stream) resolver.GetEntity (absUri, null, typeof (Stream)),
-                                               NameTable);
-                                       schema = XmlSchema.Read (xtr, ValidationEventHandler);
+                                       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 ();
+                                       if (schemas.Count != 0)
+                                               HandleError ("Could not resolve schema location URI: " + noNsSchemaLocation, null, true);
                                }
                                if (schema != null && schema.TargetNamespace != null)
                                        HandleError ("Specified schema has different target namespace.");
@@ -1624,12 +1543,6 @@ namespace Mono.Xml.Schema
                                schemas.Compile ();
                }
 
-               private bool HasMissingIDReferences ()
-               {
-                       return missingIDReferences != null
-                               && missingIDReferences.Count > 0;
-               }
-
                public override bool Read ()
                {
                        currentDefaultAttribute = -1;
@@ -1637,7 +1550,7 @@ namespace Mono.Xml.Schema
                        currentAttrType = null;
 #region ID Constraints
                        if (this.checkIdentity)
-                               thisElementId = null;
+                               idManager.OnStartElement ();
 #endregion
                        defaultAttributes = emptyAttributeArray;
 
@@ -1645,10 +1558,8 @@ namespace Mono.Xml.Schema
 #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 
@@ -1665,12 +1576,12 @@ namespace Mono.Xml.Schema
                        case XmlNodeType.Element:
 #region Key Constraints
                                if (checkKeyConstraints)
-                                       this.elementQNameStack.Add (new XmlQualifiedName (reader.LocalName, reader.NamespaceURI));
+                                       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) {
-                                       ValidateEndCharacters ();
+                                       ValidateEndSimpleContent ();
                                        AssessStartElementSchemaValidity ();
                                }
 
@@ -1774,6 +1685,21 @@ 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; }
                }
@@ -1799,4 +1725,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 []);
+               }
+       }
 }