Welcome to mirror list, hosted at ThFree Co, Russian Federation.

DocumentSchemaValidator.cs « Dom « Xml « System « System.Xml « referencesource « class « mcs - github.com/mono/mono.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 61467a7e28b7d55bb4b92878da2bc61e3547dc2e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
//------------------------------------------------------------------------------
// <copyright file="XmlDocumentValidator.cs" company="Microsoft">
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
//------------------------------------------------------------------------------

using System;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Xml;
using System.Xml.Schema;
using System.Xml.XPath;
using System.Globalization;
using System.Security;
using System.Security.Policy;
using System.Security.Permissions;
using System.Reflection;
using System.Runtime.Versioning;

namespace System.Xml {

    internal sealed class DocumentSchemaValidator : IXmlNamespaceResolver {
        XmlSchemaValidator validator;
        XmlSchemaSet schemas;
        
        XmlNamespaceManager nsManager;
        XmlNameTable nameTable;

        //Attributes
        ArrayList defaultAttributes;
        XmlValueGetter nodeValueGetter;
        XmlSchemaInfo attributeSchemaInfo;

        //Element PSVI 
        XmlSchemaInfo schemaInfo;

        //Event Handler
        ValidationEventHandler eventHandler;
        ValidationEventHandler internalEventHandler;

        //Store nodes
        XmlNode startNode;
        XmlNode currentNode;
        XmlDocument document;

        //List of nodes for partial validation tree walk
        XmlNode[] nodeSequenceToValidate;
        bool isPartialTreeValid;

        bool psviAugmentation;
        bool isValid;

        //To avoid SchemaNames creation
        private string NsXmlNs;
        private string NsXsi;
        private string XsiType;
        private string XsiNil;

        public DocumentSchemaValidator(XmlDocument ownerDocument, XmlSchemaSet schemas, ValidationEventHandler eventHandler) {
            this.schemas = schemas;
            this.eventHandler = eventHandler;
            document = ownerDocument;
            this.internalEventHandler = new ValidationEventHandler(InternalValidationCallBack);
            
            this.nameTable = document.NameTable;
            nsManager = new XmlNamespaceManager(nameTable);
            
            Debug.Assert(schemas != null && schemas.Count > 0);

            nodeValueGetter = new XmlValueGetter(GetNodeValue);
            psviAugmentation = true;

            //Add common strings to be compared to NameTable
            NsXmlNs = nameTable.Add(XmlReservedNs.NsXmlNs);
            NsXsi = nameTable.Add(XmlReservedNs.NsXsi);
            XsiType = nameTable.Add("type");
            XsiNil = nameTable.Add("nil");
        }

        public bool PsviAugmentation {
            get { return psviAugmentation; }
            set { psviAugmentation = value; }
        }

        public bool Validate(XmlNode nodeToValidate) {
            XmlSchemaObject partialValidationType = null;
            XmlSchemaValidationFlags validationFlags = XmlSchemaValidationFlags.AllowXmlAttributes;
            Debug.Assert(nodeToValidate.SchemaInfo != null);

            startNode = nodeToValidate;
            switch (nodeToValidate.NodeType) {
                case XmlNodeType.Document:
                    validationFlags |= XmlSchemaValidationFlags.ProcessIdentityConstraints;
                    break;

                case XmlNodeType.DocumentFragment:
                    break;

                case XmlNodeType.Element: //Validate children of this element
                    IXmlSchemaInfo schemaInfo = nodeToValidate.SchemaInfo;
                    XmlSchemaElement schemaElement = schemaInfo.SchemaElement;
                    if (schemaElement != null) {
                        if (!schemaElement.RefName.IsEmpty) { //If it is element ref,
                            partialValidationType = schemas.GlobalElements[schemaElement.QualifiedName]; //Get Global element with correct Nillable, Default etc
                        }
                        else { //local element
                            partialValidationType = schemaElement;
                        }
                        //Verify that if there was xsi:type, the schemaElement returned has the correct type set
                        Debug.Assert(schemaElement.ElementSchemaType == schemaInfo.SchemaType);
                    }
                    else { //Can be an element that matched xs:any and had xsi:type
                        partialValidationType = schemaInfo.SchemaType;   
                     
                        if (partialValidationType == null) { //Validated against xs:any with pc= lax or skip or undeclared / not validated element
                            if (nodeToValidate.ParentNode.NodeType == XmlNodeType.Document) {
                                //If this is the documentElement and it has not been validated at all
                                nodeToValidate = nodeToValidate.ParentNode;
                            }
                            else {
                                partialValidationType = FindSchemaInfo(nodeToValidate as XmlElement);
                                if (partialValidationType == null) { 
                                    throw new XmlSchemaValidationException(Res.XmlDocument_NoNodeSchemaInfo, null, nodeToValidate);
                                }
                            }
                        }
                    }
                    break;

                case XmlNodeType.Attribute:
                    if (nodeToValidate.XPNodeType == XPathNodeType.Namespace) goto default;
                    partialValidationType = nodeToValidate.SchemaInfo.SchemaAttribute;
                    if (partialValidationType == null) { //Validated against xs:anyAttribute with pc = lax or skip / undeclared attribute
                        partialValidationType = FindSchemaInfo(nodeToValidate as XmlAttribute);
                        if (partialValidationType == null) { 
                            throw new XmlSchemaValidationException(Res.XmlDocument_NoNodeSchemaInfo, null, nodeToValidate);
                        }
                    }
                    break;

                default:
                    throw new InvalidOperationException(Res.GetString(Res.XmlDocument_ValidateInvalidNodeType, null));
            }
            isValid = true;
            CreateValidator(partialValidationType, validationFlags);
            if (psviAugmentation) {
                if (schemaInfo == null) { //Might have created it during FindSchemaInfo
                    schemaInfo = new XmlSchemaInfo();
                }
                attributeSchemaInfo = new XmlSchemaInfo();
            }
            ValidateNode(nodeToValidate);
            validator.EndValidation();    
            return isValid; 
        }

        public IDictionary<string,string> GetNamespacesInScope(XmlNamespaceScope scope) {
            IDictionary<string,string> dictionary = nsManager.GetNamespacesInScope(scope); 
            if (scope != XmlNamespaceScope.Local) {
                XmlNode node = startNode;
                while (node != null) {
                    switch (node.NodeType) {
                        case XmlNodeType.Element:
                            XmlElement elem = (XmlElement)node;
                            if (elem.HasAttributes) {
                                XmlAttributeCollection attrs = elem.Attributes;
                                for (int i = 0; i < attrs.Count; i++) {
                                    XmlAttribute attr = attrs[i];
                                    if (Ref.Equal(attr.NamespaceURI, document.strReservedXmlns)) {
                                        if (attr.Prefix.Length == 0) {
                                            // xmlns='' declaration
                                            if (!dictionary.ContainsKey(string.Empty)) {
                                                dictionary.Add(string.Empty, attr.Value);
                                            }
                                        }
                                        else {
                                            // xmlns:prefix='' declaration
                                            if (!dictionary.ContainsKey(attr.LocalName)) {
                                                dictionary.Add(attr.LocalName, attr.Value);
                                            }
                                        }
                                    }
                                }
                            }
                            node = node.ParentNode;
                            break;
                        case XmlNodeType.Attribute:
                            node = ((XmlAttribute)node).OwnerElement;
                            break;
                        default:
                            node = node.ParentNode;
                            break;
                    }
                }
            }
            return dictionary;
        }

        public string LookupNamespace(string prefix) {
            string namespaceName = nsManager.LookupNamespace(prefix);
            if (namespaceName == null) {
                namespaceName = startNode.GetNamespaceOfPrefixStrict(prefix);
            }
            return namespaceName;
        }

        public string LookupPrefix(string namespaceName) {
            string prefix = nsManager.LookupPrefix(namespaceName);
            if (prefix == null) {
                prefix = startNode.GetPrefixOfNamespaceStrict(namespaceName);
            }
            return prefix;
        }

        private IXmlNamespaceResolver NamespaceResolver {
            get {
                if ((object)startNode == (object)document) {
                    return nsManager;
                }
                return this;
            }
        }

        private void CreateValidator(XmlSchemaObject partialValidationType, XmlSchemaValidationFlags validationFlags) {
            validator = new XmlSchemaValidator(nameTable, schemas, NamespaceResolver, validationFlags);
            validator.SourceUri = XmlConvert.ToUri(document.BaseURI);
            validator.XmlResolver = null;
            validator.ValidationEventHandler += internalEventHandler;
            validator.ValidationEventSender = this;
            
            if (partialValidationType != null) {
                validator.Initialize(partialValidationType);
            }
            else {
                validator.Initialize();
            }
        }

        private void ValidateNode(XmlNode node) {
            currentNode = node;
            switch (currentNode.NodeType) {
                case XmlNodeType.Document:
                    XmlElement docElem = ((XmlDocument)node).DocumentElement;
                    if (docElem == null) {
                        throw new InvalidOperationException(Res.GetString(Res.Xml_InvalidXmlDocument, Res.GetString(Res.Xdom_NoRootEle)));
                    }
                    ValidateNode(docElem);
                    break;

                case XmlNodeType.DocumentFragment:
                case XmlNodeType.EntityReference:
                    for (XmlNode child = node.FirstChild; child != null; child = child.NextSibling) {
                        ValidateNode(child);
                    }
                    break;

                case XmlNodeType.Element:
                    ValidateElement();
                    break;

                case XmlNodeType.Attribute: //Top-level attribute
                    XmlAttribute attr = currentNode as XmlAttribute;
                    validator.ValidateAttribute(attr.LocalName, attr.NamespaceURI, nodeValueGetter, attributeSchemaInfo);
                    if (psviAugmentation) {
                        attr.XmlName = document.AddAttrXmlName(attr.Prefix, attr.LocalName, attr.NamespaceURI, attributeSchemaInfo);
                    }
                    break;

                case XmlNodeType.Text:
                    validator.ValidateText(nodeValueGetter);
                    break;

                case XmlNodeType.CDATA:
                    validator.ValidateText(nodeValueGetter);
                    break;

                case XmlNodeType.Whitespace:
                case XmlNodeType.SignificantWhitespace:
                    validator.ValidateWhitespace(nodeValueGetter);
                    break;

                case XmlNodeType.Comment:
                case XmlNodeType.ProcessingInstruction:
                    break;

                default:
                    throw new InvalidOperationException( Res.GetString( Res.Xml_UnexpectedNodeType, new string[]{ currentNode.NodeType.ToString() } ) );
            }
        }

        // SxS: This function calls ValidateElement on XmlSchemaValidator which is annotated with ResourceExposure attribute.
        // Since the resource names passed to ValidateElement method are null and the function does not expose any resources 
        // it is fine to suppress the SxS warning. 
        [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
        [ResourceExposure(ResourceScope.None)]
        private void ValidateElement() {
            nsManager.PushScope();
            XmlElement elementNode = currentNode as XmlElement;
            Debug.Assert(elementNode != null);

            XmlAttributeCollection attributes = elementNode.Attributes;
            XmlAttribute attr = null;

            //Find Xsi attributes that need to be processed before validating the element
            string xsiNil = null;
            string xsiType = null; 

            for (int i = 0; i < attributes.Count; i++) {
                attr = attributes[i];
                string objectNs = attr.NamespaceURI;
                string objectName = attr.LocalName;
                Debug.Assert(nameTable.Get(attr.NamespaceURI) != null);
                Debug.Assert(nameTable.Get(attr.LocalName) != null);

                if (Ref.Equal(objectNs, NsXsi)) {
                    if (Ref.Equal(objectName, XsiType)) {
                        xsiType = attr.Value;
                    }
                    else if (Ref.Equal(objectName, XsiNil)) {
                        xsiNil = attr.Value;
                    }
                }
                else if (Ref.Equal(objectNs,NsXmlNs)) {
                    nsManager.AddNamespace(attr.Prefix.Length == 0 ? string.Empty : attr.LocalName, attr.Value);
                }
            }
            validator.ValidateElement(elementNode.LocalName, elementNode.NamespaceURI, schemaInfo, xsiType, xsiNil, null, null);
            ValidateAttributes(elementNode);
            validator.ValidateEndOfAttributes(schemaInfo);

            //If element has children, drill down
            for (XmlNode child = elementNode.FirstChild; child != null; child = child.NextSibling) {
                ValidateNode(child);
            }
            //Validate end of element
            currentNode = elementNode; //Reset current Node for validation call back
            validator.ValidateEndElement(schemaInfo);
            //Get XmlName, as memberType / validity might be set now
            if (psviAugmentation) {
                elementNode.XmlName = document.AddXmlName(elementNode.Prefix, elementNode.LocalName, elementNode.NamespaceURI, schemaInfo);
                if (schemaInfo.IsDefault) { //the element has a default value
                    XmlText textNode = document.CreateTextNode(schemaInfo.SchemaElement.ElementDecl.DefaultValueRaw);
                    elementNode.AppendChild(textNode);
                }
            }

            nsManager.PopScope(); //Pop current namespace scope
        }

        private void ValidateAttributes(XmlElement elementNode) {
            XmlAttributeCollection attributes = elementNode.Attributes;
            XmlAttribute attr = null;

            for (int i = 0; i < attributes.Count; i++) {
                attr = attributes[i];
                currentNode = attr; //For nodeValueGetter to pick up the right attribute value
                if (Ref.Equal(attr.NamespaceURI,NsXmlNs)) { //Do not validate namespace decls
                    continue;
                }
                validator.ValidateAttribute(attr.LocalName, attr.NamespaceURI, nodeValueGetter, attributeSchemaInfo);
                if (psviAugmentation) {
                    attr.XmlName = document.AddAttrXmlName(attr.Prefix, attr.LocalName, attr.NamespaceURI, attributeSchemaInfo);
                }
            }
    
            if (psviAugmentation) {
                //Add default attributes to the attributes collection
                if (defaultAttributes == null) {
                    defaultAttributes = new ArrayList();
                }
                else {
                    defaultAttributes.Clear();
                }
                validator.GetUnspecifiedDefaultAttributes(defaultAttributes);
                XmlSchemaAttribute schemaAttribute = null;
                XmlQualifiedName attrQName;
                attr = null;
                for (int i = 0; i < defaultAttributes.Count; i++) {
                    schemaAttribute = defaultAttributes[i] as XmlSchemaAttribute;
                    attrQName = schemaAttribute.QualifiedName;
                    Debug.Assert(schemaAttribute != null);
                    attr = document.CreateDefaultAttribute(GetDefaultPrefix(attrQName.Namespace), attrQName.Name, attrQName.Namespace);
                    SetDefaultAttributeSchemaInfo(schemaAttribute);
                    attr.XmlName = document.AddAttrXmlName(attr.Prefix, attr.LocalName, attr.NamespaceURI, attributeSchemaInfo);
                    attr.AppendChild(document.CreateTextNode(schemaAttribute.AttDef.DefaultValueRaw));
                    attributes.Append(attr);
                    XmlUnspecifiedAttribute defAttr = attr as XmlUnspecifiedAttribute;
                    if (defAttr != null) {
                        defAttr.SetSpecified(false);
                    }
                }
            }
        }

        private void SetDefaultAttributeSchemaInfo(XmlSchemaAttribute schemaAttribute) {
            Debug.Assert(attributeSchemaInfo != null);
            attributeSchemaInfo.Clear();
            attributeSchemaInfo.IsDefault = true;
            attributeSchemaInfo.IsNil = false;
            attributeSchemaInfo.SchemaType = schemaAttribute.AttributeSchemaType;
            attributeSchemaInfo.SchemaAttribute = schemaAttribute;
            
            //Get memberType for default attribute
            SchemaAttDef attributeDef = schemaAttribute.AttDef;                
            if (attributeDef.Datatype.Variety == XmlSchemaDatatypeVariety.Union) {
                XsdSimpleValue simpleValue = attributeDef.DefaultValueTyped as XsdSimpleValue;
                Debug.Assert(simpleValue != null);
                attributeSchemaInfo.MemberType = simpleValue.XmlType;
            }
            attributeSchemaInfo.Validity = XmlSchemaValidity.Valid;
        }

        private string GetDefaultPrefix(string attributeNS) {
            IDictionary<string,string> namespaceDecls = NamespaceResolver.GetNamespacesInScope(XmlNamespaceScope.All);
            string defaultPrefix = null;
            string defaultNS;
            attributeNS = nameTable.Add(attributeNS); //atomize ns

            foreach (KeyValuePair<string,string> pair in namespaceDecls) {
                defaultNS = nameTable.Add(pair.Value);
                if (object.ReferenceEquals(defaultNS, attributeNS)) {
                    defaultPrefix = pair.Key;
                    if (defaultPrefix.Length != 0) { //Locate first non-empty prefix
                        return defaultPrefix;
                    }
                }
            }
            return defaultPrefix;
        }

        private object GetNodeValue() {
            return currentNode.Value;
        }

        //Code for finding type during partial validation
        private XmlSchemaObject FindSchemaInfo(XmlElement elementToValidate) {
            isPartialTreeValid = true;
            Debug.Assert(elementToValidate.ParentNode.NodeType != XmlNodeType.Document); //Handle if it is the documentElement seperately            
            
            //Create nodelist to navigate down again
            XmlNode currentNode = elementToValidate;
            IXmlSchemaInfo parentSchemaInfo = null;
            int nodeIndex = 0;
            
            //Check common case of parent node first
            XmlNode parentNode = currentNode.ParentNode;
            do {
                parentSchemaInfo = parentNode.SchemaInfo;
                if (parentSchemaInfo.SchemaElement != null || parentSchemaInfo.SchemaType != null) {
                    break; //Found ancestor with schemaInfo
                }
                CheckNodeSequenceCapacity(nodeIndex);
                nodeSequenceToValidate[nodeIndex++] = parentNode;
                parentNode = parentNode.ParentNode;
            } while (parentNode != null);

            if (parentNode == null) { //Did not find any type info all the way to the root, currentNode is Document || DocumentFragment
                nodeIndex = nodeIndex - 1; //Subtract the one for document and set the node to null
                nodeSequenceToValidate[nodeIndex] = null;
                return GetTypeFromAncestors(elementToValidate, null, nodeIndex);
            }
            else {
                //Start validating down from the parent or ancestor that has schema info and shallow validate all previous siblings
                //to correctly ascertain particle for current node
                CheckNodeSequenceCapacity(nodeIndex);
                nodeSequenceToValidate[nodeIndex++] = parentNode;
                XmlSchemaObject ancestorSchemaObject = parentSchemaInfo.SchemaElement;
                if (ancestorSchemaObject == null) {
                    ancestorSchemaObject = parentSchemaInfo.SchemaType;
                }
                return GetTypeFromAncestors(elementToValidate, ancestorSchemaObject, nodeIndex);

            }
        }

        /*private XmlSchemaElement GetTypeFromParent(XmlElement elementToValidate, XmlSchemaComplexType parentSchemaType) {
            XmlQualifiedName elementName = new XmlQualifiedName(elementToValidate.LocalName, elementToValidate.NamespaceURI);
            XmlSchemaElement elem = parentSchemaType.LocalElements[elementName] as XmlSchemaElement;
            if (elem == null) { //Element not found as direct child of the content model. It might be invalid at this position or it might be a substitution member
                SchemaInfo compiledSchemaInfo = schemas.CompiledInfo;
                XmlSchemaElement memberElem = compiledSchemaInfo.GetElement(elementName);
                if (memberElem != null) {
                }
            }
        }*/

        private void CheckNodeSequenceCapacity(int currentIndex) {
            if (nodeSequenceToValidate == null) { //Normally users would call Validate one level down, this allows for 4
                nodeSequenceToValidate = new XmlNode[4];
            }
            else if (currentIndex >= nodeSequenceToValidate.Length -1 ) { //reached capacity of array, Need to increase capacity to twice the initial
                XmlNode[] newNodeSequence = new XmlNode[nodeSequenceToValidate.Length * 2];
                Array.Copy(nodeSequenceToValidate, 0, newNodeSequence, 0, nodeSequenceToValidate.Length);
                nodeSequenceToValidate = newNodeSequence;
            }
        }

        private XmlSchemaAttribute FindSchemaInfo(XmlAttribute attributeToValidate) {
            XmlElement parentElement = attributeToValidate.OwnerElement;
            XmlSchemaObject schemaObject = FindSchemaInfo(parentElement);
            XmlSchemaComplexType elementSchemaType = GetComplexType(schemaObject);
            if (elementSchemaType == null) {
                return null;
            }
            XmlQualifiedName attName = new XmlQualifiedName(attributeToValidate.LocalName, attributeToValidate.NamespaceURI);
            XmlSchemaAttribute schemaAttribute = elementSchemaType.AttributeUses[attName] as XmlSchemaAttribute;
            if (schemaAttribute == null) {
                XmlSchemaAnyAttribute anyAttribute = elementSchemaType.AttributeWildcard;
                if (anyAttribute != null) {
                    if (anyAttribute.NamespaceList.Allows(attName)){ //Match wildcard against global attribute
                        schemaAttribute = schemas.GlobalAttributes[attName] as XmlSchemaAttribute;
                    }
                }
            }
            return schemaAttribute;
        }

        private XmlSchemaObject GetTypeFromAncestors(XmlElement elementToValidate, XmlSchemaObject ancestorType, int ancestorsCount) {
            
            //schemaInfo is currentNode's schemaInfo
            validator = CreateTypeFinderValidator(ancestorType);
            schemaInfo = new XmlSchemaInfo();

            //start at the ancestor to start validating
            int startIndex = ancestorsCount - 1;
        
            bool ancestorHasWildCard = AncestorTypeHasWildcard(ancestorType);
            for (int i = startIndex; i >= 0; i--) {
                XmlNode node = nodeSequenceToValidate[i];
                XmlElement currentElement = node as XmlElement;
                ValidateSingleElement(currentElement, false, schemaInfo);
                if (!ancestorHasWildCard) { //store type if ancestor does not have wildcard in its content model
                    currentElement.XmlName = document.AddXmlName(currentElement.Prefix, currentElement.LocalName, currentElement.NamespaceURI, schemaInfo);
                    //update wildcard flag
                    ancestorHasWildCard = AncestorTypeHasWildcard(schemaInfo.SchemaElement);
                }
                
                validator.ValidateEndOfAttributes(null);
                if (i > 0) {
                    ValidateChildrenTillNextAncestor(node, nodeSequenceToValidate[i - 1]);
                }
                else { //i == 0
                    ValidateChildrenTillNextAncestor(node, elementToValidate);
                }
            }

            Debug.Assert(nodeSequenceToValidate[0] == elementToValidate.ParentNode);
            //validate element whose type is needed,
            ValidateSingleElement(elementToValidate, false, schemaInfo);

            XmlSchemaObject schemaInfoFound = null;
            if (schemaInfo.SchemaElement != null) {
                schemaInfoFound = schemaInfo.SchemaElement;
            }
            else {
                schemaInfoFound = schemaInfo.SchemaType;
            }
            if (schemaInfoFound == null) { //Detect if the node was validated lax or skip
                if (validator.CurrentProcessContents == XmlSchemaContentProcessing.Skip) {
                    if (isPartialTreeValid) { //Then node assessed as skip; if there was error we turn processContents to skip as well. But this is not the same as validating as skip.
                        return XmlSchemaComplexType.AnyTypeSkip;
                    }
                }
                else if (validator.CurrentProcessContents == XmlSchemaContentProcessing.Lax) {
                    return XmlSchemaComplexType.AnyType;
                }
            }
            return schemaInfoFound;
        }

        private bool AncestorTypeHasWildcard(XmlSchemaObject ancestorType) {
            XmlSchemaComplexType ancestorSchemaType = GetComplexType(ancestorType);
            if (ancestorType != null) {
                return ancestorSchemaType.HasWildCard;
            }
            return false;
        }

        private XmlSchemaComplexType GetComplexType(XmlSchemaObject schemaObject) {
            if (schemaObject == null) {
                return null;
            }
            XmlSchemaElement schemaElement = schemaObject as XmlSchemaElement;
            XmlSchemaComplexType complexType = null;
            if (schemaElement != null) {
                complexType = schemaElement.ElementSchemaType as XmlSchemaComplexType;
            }
            else {
                complexType = schemaObject as XmlSchemaComplexType;
            }
            return complexType;
        }

        // SxS: This function calls ValidateElement on XmlSchemaValidator which is annotated with ResourceExposure attribute.
        // Since the resource names passed to ValidateElement method are null and the function does not expose any resources 
        // it is fine to supress the warning. 
        [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
        [ResourceExposure(ResourceScope.None)]
        private void ValidateSingleElement(XmlElement elementNode, bool skipToEnd, XmlSchemaInfo newSchemaInfo) {
            nsManager.PushScope();
            Debug.Assert(elementNode != null);
            
            XmlAttributeCollection attributes = elementNode.Attributes;
            XmlAttribute attr = null;

            //Find Xsi attributes that need to be processed before validating the element
            string xsiNil = null;
            string xsiType = null; 

            for (int i = 0; i < attributes.Count; i++) {
                attr = attributes[i];
                string objectNs = attr.NamespaceURI;
                string objectName = attr.LocalName;
                Debug.Assert(nameTable.Get(attr.NamespaceURI) != null);
                Debug.Assert(nameTable.Get(attr.LocalName) != null);

                if (Ref.Equal(objectNs, NsXsi)) {
                    if (Ref.Equal(objectName, XsiType)) {
                        xsiType = attr.Value;
                    }
                    else if (Ref.Equal(objectName, XsiNil)) {
                        xsiNil = attr.Value;
                    }
                }
                else if (Ref.Equal(objectNs,NsXmlNs)) {
                    nsManager.AddNamespace(attr.Prefix.Length == 0 ? string.Empty : attr.LocalName, attr.Value);
                }
            }
            validator.ValidateElement(elementNode.LocalName, elementNode.NamespaceURI, newSchemaInfo, xsiType, xsiNil, null, null);
            //Validate end of element
            if (skipToEnd) {
                validator.ValidateEndOfAttributes(newSchemaInfo);
                validator.SkipToEndElement(newSchemaInfo);
                nsManager.PopScope(); //Pop current namespace scope
            }
        }

        private void ValidateChildrenTillNextAncestor(XmlNode parentNode, XmlNode childToStopAt) {
            XmlNode child;

            for (child = parentNode.FirstChild; child != null; child = child.NextSibling) {
                if (child == childToStopAt) {
                    break;
                }
                switch (child.NodeType) {
                    case XmlNodeType.EntityReference:
                        ValidateChildrenTillNextAncestor(child, childToStopAt);
                        break;

                    case XmlNodeType.Element: //Flat validation, do not drill down into children
                        ValidateSingleElement(child as XmlElement, true, null);
                        break;

                    case XmlNodeType.Text:
                    case XmlNodeType.CDATA:
                        validator.ValidateText(child.Value);
                        break;

                    case XmlNodeType.Whitespace:
                    case XmlNodeType.SignificantWhitespace:
                        validator.ValidateWhitespace(child.Value);
                        break;

                    case XmlNodeType.Comment:
                    case XmlNodeType.ProcessingInstruction:
                        break;

                    default:
                        throw new InvalidOperationException( Res.GetString( Res.Xml_UnexpectedNodeType, new string[]{ currentNode.NodeType.ToString() } ) );
                }
            }
            Debug.Assert(child == childToStopAt);
        }

        private XmlSchemaValidator CreateTypeFinderValidator(XmlSchemaObject partialValidationType) {
            XmlSchemaValidator findTypeValidator = new XmlSchemaValidator(document.NameTable, document.Schemas, this.nsManager, XmlSchemaValidationFlags.None);
            findTypeValidator.ValidationEventHandler += new ValidationEventHandler(TypeFinderCallBack);
            if (partialValidationType != null) {
                findTypeValidator.Initialize(partialValidationType);
            }
            else { //If we walked up to the root and no schemaInfo was there, start validating from root 
                findTypeValidator.Initialize();
            }
            return findTypeValidator;
        }

        private void TypeFinderCallBack(object sender, ValidationEventArgs arg) {
            if (arg.Severity == XmlSeverityType.Error) {
                isPartialTreeValid = false;
            }
        }
        
        private void InternalValidationCallBack(object sender, ValidationEventArgs arg) {
            if (arg.Severity == XmlSeverityType.Error) {
                isValid = false;
            }
            XmlSchemaValidationException ex = arg.Exception as XmlSchemaValidationException;
            Debug.Assert(ex != null);
            ex.SetSourceObject(currentNode);
            if (this.eventHandler != null) { //Invoke user's event handler
                eventHandler(sender, arg);
            }
            else if (arg.Severity == XmlSeverityType.Error) {
                throw ex;
            }
        }

    }
}