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

DTDValidatingReader.cs « System.Xml « System.XML « class « mcs - github.com/mono/mono.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 7fd1790f0f2687a3dd277ca1327ebded7122c0dd (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
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
//
// DTDValidatingReader.cs
//
// Author:
//   Atsushi Enomoto  (ginga@kit.hi-ho.ne.jp)
//
// (C)2003 Atsushi Enomoto
// (C)2004 Novell Inc.
//

//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// 
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
#if NET_2_0
using System.Collections.Generic;
#endif
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Schema;

#if NET_2_0
using XmlTextReaderImpl = Mono.Xml2.XmlTextReader;
#else
using XmlTextReaderImpl = System.Xml.XmlTextReader;
#endif


namespace Mono.Xml
{
#if NET_2_0
	internal class DTDValidatingReader : XmlReader, IXmlLineInfo, IHasXmlParserContext, IHasXmlSchemaInfo, IXmlNamespaceResolver
#else
	internal class DTDValidatingReader : XmlReader, IXmlLineInfo, IHasXmlParserContext, IHasXmlSchemaInfo
#endif
	{
		public DTDValidatingReader (XmlReader reader)
			: this (reader, null)
		{
		}

		internal DTDValidatingReader (XmlReader reader,
			XmlValidatingReader validatingReader)
		{
			entityReaderStack = new Stack ();
			entityReaderDepthStack = new Stack ();
			this.reader = reader;
			this.sourceTextReader = reader as XmlTextReader;
			elementStack = new Stack ();
			automataStack = new Stack ();
			attributes = new ArrayList ();
			attributeValues = new Hashtable ();
			attributeLocalNames = new Hashtable ();
			attributeNamespaces = new Hashtable ();
			attributePrefixes = new Hashtable ();
			nsmgr = new XmlNamespaceManager (reader.NameTable);
			this.validatingReader = validatingReader;
			valueBuilder = new StringBuilder ();
			idList = new ArrayList ();
			missingIDReferences = new ArrayList ();
			XmlTextReader xtReader = reader as XmlTextReader;
			if (xtReader != null) {
				resolver = xtReader.Resolver;
			}
			else
				resolver = new XmlUrlResolver ();
		}

		Stack entityReaderStack;
		Stack entityReaderDepthStack;
		XmlReader reader;
		XmlTextReader sourceTextReader;
		XmlTextReader nextEntityReader;
		DTDObjectModel dtd;
		Stack elementStack;
		Stack automataStack;
		string currentElement;
		string currentAttribute;
		string currentTextValue;
		string constructingTextValue;
		bool shouldResetCurrentTextValue;
		bool consumedAttribute;
		bool insideContent;
		DTDAutomata currentAutomata;
		DTDAutomata previousAutomata;
		bool isStandalone;
		ArrayList attributes;
		Hashtable attributeValues;
		Hashtable attributeLocalNames;
		Hashtable attributeNamespaces;
		Hashtable attributePrefixes;
		XmlNamespaceManager nsmgr;
		StringBuilder valueBuilder;
		ArrayList idList;
		ArrayList missingIDReferences;
		XmlResolver resolver;
		EntityHandling currentEntityHandling;
		bool isSignificantWhitespace;
		bool isWhitespace;
		bool isText;
		bool dontResetTextType;
		bool popScope;

		// This field is used to get properties and to raise events.
		XmlValidatingReader validatingReader;

		public DTDObjectModel DTD {
			get { return dtd; }
		}

		public EntityHandling EntityHandling {
			get { return currentEntityHandling; }
			set { currentEntityHandling = value; }
		}

		public override void Close ()
		{
			reader.Close ();
		}

		// We had already done attribute validation, so can ignore name.
		public override string GetAttribute (int i)
		{
			if (currentTextValue != null)
				throw new IndexOutOfRangeException ("Specified index is out of range: " + i);

			if (dtd == null)
				return reader.GetAttribute (i);

			if (attributes.Count <= i)
				throw new IndexOutOfRangeException ("Specified index is out of range: " + i);

			string attrName = (string) attributes [i];
			return FilterNormalization (attrName, (string) attributeValues [attrName]);
		}

		public override string GetAttribute (string name)
		{
			if (currentTextValue != null)
				return null;

			if (dtd == null)
				return reader.GetAttribute (name);

			return FilterNormalization (name, (string) attributeValues [name]);
		}

		public override string GetAttribute (string name, string ns)
		{
			if (currentTextValue != null)
				return null;

			if (dtd == null)
				return reader.GetAttribute (name, ns);

			return reader.GetAttribute ((string) attributeLocalNames [name], ns);
		}

#if NET_2_0
		IDictionary<string, string> IXmlNamespaceResolver.GetNamespacesInScope (XmlNamespaceScope scope)
		{
			IXmlNamespaceResolver res = reader as IXmlNamespaceResolver;
			return res != null ? res.GetNamespacesInScope (scope) : new Dictionary<string, string> ();
		}
#endif

		bool IXmlLineInfo.HasLineInfo ()
		{
			IXmlLineInfo ixli = reader as IXmlLineInfo;
			if (ixli != null)
				return ixli.HasLineInfo ();
			else
				return false;
		}

		public override string LookupNamespace (string prefix)
		{
			string s = nsmgr.LookupNamespace (NameTable.Get (prefix));
			return s == String.Empty ? null : s;
		}

#if NET_2_0
		string IXmlNamespaceResolver.LookupPrefix (string ns)
		{
			IXmlNamespaceResolver res = reader as IXmlNamespaceResolver;
			return res != null ? res.LookupPrefix (ns) : null;
		}
#endif

		public override void MoveToAttribute (int i)
		{
			if (currentTextValue != null)
				throw new IndexOutOfRangeException ("The index is out of range.");

			if (dtd == null) {
				reader.MoveToAttribute (i);
				currentAttribute = reader.Name;
				consumedAttribute = false;
				return;
			}

			if (currentElement == null)
				throw new IndexOutOfRangeException ("The index is out of range.");

			if (attributes.Count > i) {
				if (reader.AttributeCount > i)
					reader.MoveToAttribute (i);
				currentAttribute = (string) attributes [i];
				consumedAttribute = false;
				return;
			} else
				throw new IndexOutOfRangeException ("The index is out of range.");
		}

		public override bool MoveToAttribute (string name)
		{
			if (currentTextValue != null)
				return false;

			if (dtd == null) {
				bool b = reader.MoveToAttribute (name);
				if (b) {
					currentAttribute = reader.Name;
					consumedAttribute = false;
				}
				return b;
			}

			if (currentElement == null)
				return false;

			int idx = attributes.IndexOf (name);
			if (idx >= 0) {
				currentAttribute = name;
				consumedAttribute = false;
				return true;
			}
			return false;
		}

		public override bool MoveToAttribute (string name, string ns)
		{
			if (currentTextValue != null)
				return false;

			if (dtd == null) {
				bool b = reader.MoveToAttribute (name, ns);
				if (b) {
					currentAttribute = reader.Name;
					consumedAttribute = false;
				}
				return b;
			}

			if (reader.MoveToAttribute (name, ns)) {
				currentAttribute = reader.Name;
				consumedAttribute = false;
				return true;
			}

			for (int i = 0; i < attributes.Count; i++) {
				string iter = (string) attributes [i];
				if ((string) attributeLocalNames [iter] == name)
					return MoveToAttribute (iter);
			}
			return false;
		}

		public override bool MoveToElement ()
		{
			if (currentTextValue != null)
				return false;

			bool b = reader.MoveToElement ();
			if (!b && !IsDefault)
				return false;
			currentAttribute = null;
			consumedAttribute = false;
			return true;
		}

		public override bool MoveToFirstAttribute ()
		{
			if (currentTextValue != null)
				return false;

			if (dtd == null) {
				bool b = reader.MoveToFirstAttribute ();
				if (b) {
					currentAttribute = reader.Name;
					consumedAttribute = false;
				}
				return b;
			}

			if (attributes.Count == 0)
				return false;
			currentAttribute = (string) attributes [0];
			reader.MoveToAttribute (currentAttribute);
			consumedAttribute = false;
			return true;
		}

		public override bool MoveToNextAttribute ()
		{
			if (currentTextValue != null)
				return false;

			if (dtd == null) {
				bool b = reader.MoveToNextAttribute ();
				if (b) {
					currentAttribute = reader.Name;
					consumedAttribute = false;
				}
				return b;
			}

			if (currentAttribute == null)
				return MoveToFirstAttribute ();

			int idx = attributes.IndexOf (currentAttribute);
			if (idx + 1 < attributes.Count) {
				currentAttribute = (string) attributes [idx + 1];
				reader.MoveToAttribute (currentAttribute);
				consumedAttribute = false;
				return true;
			} else
				return false;
		}

		/*
		private void OnValidationEvent (object o, ValidationEventArgs e)
		{
			this.HandleError (e.Exception, e.Severity);
		}
		*/

		public override bool Read ()
		{
			if (currentTextValue != null)
				shouldResetCurrentTextValue = true;

			MoveToElement ();

			currentElement = null;
			currentAttribute = null;
			consumedAttribute = false;
			attributes.Clear ();
			attributeLocalNames.Clear ();
			attributeValues.Clear ();
			attributeNamespaces.Clear ();
			attributePrefixes.Clear ();
			isWhitespace = false;
			isSignificantWhitespace = false;
			isText = false;
			dontResetTextType = false;

			bool b = ReadContent () || currentTextValue != null;
			if (!b && this.missingIDReferences.Count > 0) {
				this.HandleError ("Missing ID reference was found: " +
					String.Join (",", missingIDReferences.ToArray (typeof (string)) as string []),
					XmlSeverityType.Error);
				// Don't output the same errors so many times.
				this.missingIDReferences.Clear ();
			}
			if (validatingReader != null)
				EntityHandling = validatingReader.EntityHandling;
			return b;
		}

		private bool ReadContent ()
		{
			if (popScope) {
				nsmgr.PopScope ();
				popScope = false;
			}
			if (nextEntityReader != null) {
				if (DTD == null || DTD.EntityDecls [reader.Name] == null)
					throw NotWFError (String.Format ("Entity '{0}' was not declared.", reader.Name));
				entityReaderStack.Push (reader);
				entityReaderDepthStack.Push (Depth);
				reader = sourceTextReader = nextEntityReader;
				nextEntityReader = null;
				return ReadContent ();
			} else if (reader.EOF && entityReaderStack.Count > 0) {
				reader.Close ();
				reader = entityReaderStack.Pop () as XmlReader;
				entityReaderDepthStack.Pop ();
				sourceTextReader = reader as XmlTextReader;
				return ReadContent ();
			}

			bool b = !reader.EOF;
			if (shouldResetCurrentTextValue) {
				currentTextValue = null;
				shouldResetCurrentTextValue = false;
			}
			else
				b = reader.Read ();

			if (!insideContent && reader.NodeType == XmlNodeType.Element) {
				insideContent = true;
				if (dtd == null)
					currentAutomata = null;
				else
					currentAutomata = dtd.RootAutomata;
			}

			if (!b) {
				if (entityReaderStack.Count > 0) {
					if (validatingReader.EntityHandling == EntityHandling.ExpandEntities)
						return ReadContent ();
					else
						return true;	// EndEntity
				}

				if (elementStack.Count != 0)
					throw new InvalidOperationException ("Unexpected end of XmlReader.");
				return false;
			}

			DTDElementDeclaration elem = null;

			switch (reader.NodeType) {
			case XmlNodeType.XmlDeclaration:
				if (GetAttribute ("standalone") == "yes")
					isStandalone = true;
				ValidateAttributes (null, false);
				break;

			case XmlNodeType.DocumentType:
//				XmlTextReader xmlTextReader = reader as XmlTextReader;
				IHasXmlParserContext ctx = reader as IHasXmlParserContext;
				if (ctx != null)
					dtd = ctx.ParserContext.Dtd;
				if (dtd == null) {
					XmlTextReaderImpl xmlTextReader = new XmlTextReaderImpl ("", XmlNodeType.Document, null);
					xmlTextReader.XmlResolver = resolver;
					xmlTextReader.GenerateDTDObjectModel (reader.Name,
						reader ["PUBLIC"], reader ["SYSTEM"], reader.Value);
					dtd = xmlTextReader.DTD;
				}

				// Validity Constraints Check.
				if (DTD.Errors.Length > 0)
					for (int i = 0; i < DTD.Errors.Length; i++)
						HandleError (DTD.Errors [i].Message, XmlSeverityType.Error);

				// NData target exists.
				foreach (DTDEntityDeclaration ent in dtd.EntityDecls.Values)
					if (ent.NotationName != null && dtd.NotationDecls [ent.NotationName] == null)
						this.HandleError ("Target notation was not found for NData in entity declaration " + ent.Name + ".",
							XmlSeverityType.Error);
				// NOTATION exists for attribute default values
				foreach (DTDAttListDeclaration attListIter in dtd.AttListDecls.Values)
					foreach (DTDAttributeDefinition def in attListIter.Definitions)
						if (def.Datatype.TokenizedType == XmlTokenizedType.NOTATION) {
							foreach (string notation in def.EnumeratedNotations)
								if (dtd.NotationDecls [notation] == null)
									this.HandleError ("Target notation was not found for NOTATION typed attribute default " + def.Name + ".",
										XmlSeverityType.Error);
						}

				break;

			case XmlNodeType.Element:
				nsmgr.PushScope ();
				popScope = reader.IsEmptyElement;
				if (constructingTextValue != null) {
					currentTextValue = constructingTextValue;
					constructingTextValue = null;
					if (isWhitespace)
						ValidateWhitespaceNode ();
					return true;
				}
				elementStack.Push (reader.Name);
				// startElementDeriv
				// If no schema specification, then skip validation.
				if (currentAutomata == null) {
					ValidateAttributes (null, false);
					if (reader.IsEmptyElement)
						goto case XmlNodeType.EndElement;
					break;
				}

				previousAutomata = currentAutomata;
				currentAutomata = currentAutomata.TryStartElement (reader.Name);
				if (currentAutomata == DTD.Invalid) {
					HandleError (String.Format ("Invalid start element found: {0}", reader.Name),
						XmlSeverityType.Error);
					currentAutomata = previousAutomata;
				}
				elem = DTD.ElementDecls [reader.Name];
				if (elem == null) {
					HandleError (String.Format ("Element {0} is not declared.", reader.Name),
						XmlSeverityType.Error);
					currentAutomata = previousAutomata;
				}

				currentElement = Name;
				automataStack.Push (currentAutomata);
				if (elem != null)	// i.e. not invalid
					currentAutomata = elem.ContentModel.GetAutomata ();

				DTDAttListDeclaration attList = dtd.AttListDecls [currentElement];
				if (attList != null) {
					// check attributes
					ValidateAttributes (attList, true);
					currentAttribute = null;
				} else {
					if (reader.HasAttributes) {
						HandleError (String.Format (
							"Attributes are found on element {0} while it has no attribute definitions.", currentElement),
							XmlSeverityType.Error);
					}
					// SetupValidityIgnorantAttributes ();
					ValidateAttributes (null, false);
				}
				// If it is empty element then directly check end element.
				if (reader.IsEmptyElement)
					goto case XmlNodeType.EndElement;
				break;

			case XmlNodeType.EndElement:
				if (constructingTextValue != null) {
					currentTextValue = constructingTextValue;
					constructingTextValue = null;
					return true;
				}
				popScope = true;
				elementStack.Pop ();
				// endElementDeriv
				// If no schema specification, then skip validation.
				if (currentAutomata == null)
					break;

				elem = DTD.ElementDecls [reader.Name];
				if (elem == null) {
					HandleError (String.Format ("Element {0} is not declared.", reader.Name),
						XmlSeverityType.Error);
				}

				previousAutomata = currentAutomata;
				// Don't let currentAutomata
				DTDAutomata tmpAutomata = currentAutomata.TryEndElement ();
				if (tmpAutomata == DTD.Invalid) {
					HandleError (String.Format ("Invalid end element found: {0}", reader.Name),
						XmlSeverityType.Error);
					currentAutomata = previousAutomata;
				}

				currentAutomata = automataStack.Pop () as DTDAutomata;
				break;

			case XmlNodeType.CDATA:
				isSignificantWhitespace = isWhitespace = false;
				isText = true;

				ValidateText ();

				if (currentTextValue != null) {
					currentTextValue = constructingTextValue;
					constructingTextValue = null;
					return true;
				}
				break;
			case XmlNodeType.SignificantWhitespace:
				if (!isText)
					isSignificantWhitespace = true;
				isWhitespace = false;
				dontResetTextType = true;
				goto case XmlNodeType.DocumentFragment;
			case XmlNodeType.Text:
				isWhitespace = isSignificantWhitespace = false;
				isText = true;
				goto case XmlNodeType.DocumentFragment;
			case XmlNodeType.DocumentFragment:
				// it should not happen, but in case if
				// XmlReader really returns it, just ignore.
				if (reader.NodeType == XmlNodeType.DocumentFragment)
					break;

				ValidateText ();

				if (entityReaderStack.Count > 0 && validatingReader.EntityHandling == EntityHandling.ExpandEntities) {
					constructingTextValue += reader.Value;
					return ReadContent ();
				}
				break;
			case XmlNodeType.Whitespace:
				if (!isText && !isSignificantWhitespace)
					isWhitespace = true;
				goto case XmlNodeType.DocumentFragment;
			case XmlNodeType.EntityReference:
				if (validatingReader.EntityHandling == EntityHandling.ExpandEntities) {
					ResolveEntity ();
					return ReadContent ();
				}
				break;
			}
			if (isWhitespace)
				ValidateWhitespaceNode ();
			currentTextValue = constructingTextValue;
			constructingTextValue = null;
			MoveToElement ();
			return true;
		}

		private void ValidateText ()
		{
			if (currentAutomata == null)
				return;

			DTDElementDeclaration elem = null;
			if (elementStack.Count > 0)
				elem = dtd.ElementDecls [elementStack.Peek () as string];
			// Here element should have been already validated, so
			// if no matching declaration is found, simply ignore.
			if (elem != null && !elem.IsMixedContent && !elem.IsAny && !isWhitespace) {
				HandleError (String.Format ("Current element {0} does not allow character data content.", elementStack.Peek () as string),
					XmlSeverityType.Error);
				currentAutomata = previousAutomata;
			}
		}

		private void ValidateWhitespaceNode ()
		{
			// VC Standalone Document Declaration (2.9)
			if (this.isStandalone && DTD != null && elementStack.Count > 0) {
				DTDElementDeclaration elem = DTD.ElementDecls [elementStack.Peek () as string];
				if (elem != null && !elem.IsInternalSubset && !elem.IsMixedContent && !elem.IsAny && !elem.IsEmpty)
					HandleError ("In standalone document, whitespace cannot appear in an element whose declaration explicitly contains child content model, not Mixed content.", XmlSeverityType.Error);
			}
		}

		private XmlException NotWFError (string message)
		{
			return new XmlException (this as IXmlLineInfo, BaseURI, message);
		}

		private void HandleError (string message, XmlSeverityType severity)
		{
			if (validatingReader != null &&
				validatingReader.ValidationType == ValidationType.None)
				return;

			IXmlLineInfo info = this as IXmlLineInfo;
			bool hasLine = info.HasLineInfo ();
			XmlSchemaException ex = new XmlSchemaException (
				message,
				hasLine ? info.LineNumber : 0,
				hasLine ? info.LinePosition : 0, 
				null,
				BaseURI, 
				null);
			HandleError (ex, severity);
		}

		private void HandleError (XmlSchemaException ex, XmlSeverityType severity)
		{
			if (validatingReader != null &&
				validatingReader.ValidationType == ValidationType.None)
				return;

			if (validatingReader != null)
				this.validatingReader.OnValidationEvent (this,
					new ValidationEventArgs (ex, ex.Message, severity));
			else if (severity == XmlSeverityType.Error)
				throw ex;
		}

		Stack attributeValueEntityStack = new Stack ();

		private void ValidateAttributes (DTDAttListDeclaration decl, bool validate)
		{
			DtdValidateAttributes (decl, validate);

			foreach (string attr in attributes)
				if (attr == "xmlns" ||
					String.CompareOrdinal (attr, 0, "xmlns:", 0, 6) == 0)
					nsmgr.AddNamespace (
						attr == "xmlns" ? String.Empty : (string) attributeLocalNames [attr],
						(string) attributeValues [attr]);

			foreach (string attr in attributes) {
				string prefix = attr == "xmlns" ? "xmlns" : attributePrefixes [attr] as string;
				if (prefix == String.Empty)
					attributeNamespaces.Add (attr, String.Empty);
				else
					attributeNamespaces.Add (attr, LookupNamespace (prefix));
			}
		}

		private void DtdValidateAttributes (DTDAttListDeclaration decl, bool validate)
		{
			while (reader.MoveToNextAttribute ()) {
				string attrName = reader.Name;
				this.currentAttribute = attrName;
				attributes.Add (attrName);
				attributeLocalNames.Add (attrName, reader.LocalName);
				attributePrefixes.Add (attrName, reader.Prefix);
				XmlReader targetReader = reader;
				string attrValue = null;
				// It always resolves entity references on attributes (documented as such).
//				if (currentEntityHandling == EntityHandling.ExpandCharEntities)
//					attrValue = reader.Value;
//				else
				{
					while (attributeValueEntityStack.Count >= 0) {
						if (!targetReader.ReadAttributeValue ()) {
							if (attributeValueEntityStack.Count > 0) {
								targetReader = attributeValueEntityStack.Pop () as XmlReader;
								continue;
							} else
								break;
						}
						switch (targetReader.NodeType) {
						case XmlNodeType.EntityReference:
							DTDEntityDeclaration edecl = DTD.EntityDecls [targetReader.Name];
							if (edecl == null) {
								HandleError (String.Format ("Referenced entity {0} is not declared.", targetReader.Name),
									XmlSeverityType.Error);
							} else {
								XmlTextReader etr = new XmlTextReader (edecl.EntityValue, XmlNodeType.Attribute, ParserContext);
								attributeValueEntityStack.Push (targetReader);
								targetReader = etr;
								continue;
							}
							break;
						case XmlNodeType.EndEntity:
							break;
						default:
							if (attrValue != null) {
								valueBuilder.Append (attrValue);
								attrValue = null;
							}
							
							if (valueBuilder.Length != 0)
								valueBuilder.Append (targetReader.Value);
							else
								attrValue = targetReader.Value;
							
							break;
						}
					}
					
					if (attrValue == null) {
						attrValue = valueBuilder.ToString ();
						valueBuilder.Length = 0;
					}
				}
				reader.MoveToElement ();
				reader.MoveToAttribute (attrName);
				attributeValues.Add (attrName, attrValue);

				if (!validate)
					continue;

				// Validation

				DTDAttributeDefinition def = decl [reader.Name];
				if (def == null) {
					HandleError (String.Format ("Attribute {0} is not declared.", reader.Name),
						XmlSeverityType.Error);
					continue;
				}

				// check enumeration constraint
				if (def.EnumeratedAttributeDeclaration.Count > 0)
					if (!def.EnumeratedAttributeDeclaration.Contains (
						FilterNormalization (reader.Name, attrValue)))
						HandleError (String.Format ("Attribute enumeration constraint error in attribute {0}, value {1}.",
							reader.Name, attrValue), XmlSeverityType.Error);
				if (def.EnumeratedNotations.Count > 0)
					if (!def.EnumeratedNotations.Contains (
						FilterNormalization (reader.Name, attrValue)))
						HandleError (String.Format ("Attribute notation enumeration constraint error in attribute {0}, value {1}.",
							reader.Name, attrValue), XmlSeverityType.Error);

				// check type constraint
				string normalized = null;
				if (def.Datatype != null)
					normalized = FilterNormalization (def.Name, attrValue);
				else
					normalized = attrValue;
				DTDEntityDeclaration ent;

				// Common process to get list value
				string [] list = null;
				switch (def.Datatype.TokenizedType) {
				case XmlTokenizedType.IDREFS:
				case XmlTokenizedType.ENTITIES:
				case XmlTokenizedType.NMTOKENS:
					try {
						list = def.Datatype.ParseValue (normalized, NameTable, null) as string [];
					} catch (Exception) {
						HandleError ("Attribute value is invalid against its data type.", XmlSeverityType.Error);
						list = new string [0];
					}
					break;
				default:
					try {
						def.Datatype.ParseValue (normalized, NameTable, null);
					} catch (Exception ex) {
						HandleError (String.Format ("Attribute value is invalid against its data type '{0}'. {1}", def.Datatype, ex.Message), XmlSeverityType.Error);
					}
					break;
				}

				switch (def.Datatype.TokenizedType) {
				case XmlTokenizedType.ID:
					if (this.idList.Contains (normalized)) {
						HandleError (String.Format ("Node with ID {0} was already appeared.", attrValue),
							XmlSeverityType.Error);
					} else {
						if (missingIDReferences.Contains (normalized))
							missingIDReferences.Remove (normalized);
						idList.Add (normalized);
					}
					break;
				case XmlTokenizedType.IDREF:
					if (!idList.Contains (normalized))
						missingIDReferences.Add (normalized);
					break;
				case XmlTokenizedType.IDREFS:
					for (int i = 0; i < list.Length; i++) {
						string idref = list [i];
						if (!idList.Contains (idref))
							missingIDReferences.Add (idref);
					}
					break;
				case XmlTokenizedType.ENTITY:
					ent = dtd.EntityDecls [normalized];
					if (ent == null)
						HandleError ("Reference to undeclared entity was found in attribute: " + reader.Name + ".", XmlSeverityType.Error);
					else if (ent.NotationName == null)
						HandleError ("The entity specified by entity type value must be an unparsed entity. The entity definition has no NDATA in attribute: " + reader.Name + ".", XmlSeverityType.Error);
					break;
				case XmlTokenizedType.ENTITIES:
					for (int i = 0; i < list.Length; i++) {
						string entref = list [i];
						ent = dtd.EntityDecls [FilterNormalization (reader.Name, entref)];
						if (ent == null)
							HandleError ("Reference to undeclared entity was found in attribute: " + reader.Name + ".", XmlSeverityType.Error);
						else if (ent.NotationName == null)
							HandleError ("The entity specified by ENTITIES type value must be an unparsed entity. The entity definition has no NDATA in attribute: " + reader.Name + ".", XmlSeverityType.Error);
					}
					break;
//				case XmlTokenizedType.NMTOKEN: nothing to do
//				case XmlTokenizedType.NMTOKENS: nothing to do
				}

				if (isStandalone && !def.IsInternalSubset && 
					attrValue != normalized)
					HandleError ("In standalone document, attribute value characters must not be checked against external definition.", XmlSeverityType.Error);

				if (def.OccurenceType == 
					DTDAttributeOccurenceType.Fixed &&
					attrValue != def.DefaultValue)
					HandleError (String.Format ("Fixed attribute {0} in element {1} has invalid value {2}.",
						def.Name, decl.Name, attrValue),
						XmlSeverityType.Error);
			}

			if (validate)
				VerifyDeclaredAttributes (decl);

			MoveToElement ();
		}

		private void VerifyDeclaredAttributes (DTDAttListDeclaration decl)
		{
			// Check if all required attributes exist, and/or
			// if there is default values, then add them.
			for (int i = 0; i < decl.Definitions.Count; i++) {
				DTDAttributeDefinition def = (DTDAttributeDefinition) decl.Definitions [i];
				if (attributes.Contains (def.Name))
					continue;

				if (def.OccurenceType == DTDAttributeOccurenceType.Required) {
					HandleError (String.Format ("Required attribute {0} in element {1} not found .",
						def.Name, decl.Name),
						XmlSeverityType.Error);
					continue;
				}

				else if (def.DefaultValue == null)
					continue;

				if (this.isStandalone && !def.IsInternalSubset)
					HandleError ("In standalone document, external default value definition must not be applied.", XmlSeverityType.Error);

				switch (validatingReader.ValidationType) {
				case ValidationType.Auto:
					if (validatingReader.Schemas.Count == 0)
						goto case ValidationType.DTD;
					break;
				case ValidationType.DTD:
				case ValidationType.None:
					// Other than them, ignore DTD defaults.
					attributes.Add (def.Name);
					int colonAt = def.Name.IndexOf (':');
					attributeLocalNames.Add (def.Name,
						colonAt < 0 ? def.Name :
						def.Name.Substring (colonAt + 1));
					string prefix = colonAt < 0 ?
						String.Empty :
						def.Name.Substring (0, colonAt);
					attributePrefixes.Add (def.Name, prefix);
					attributeValues.Add (def.Name, def.DefaultValue);
					break;
				}
			}
		}

		public override bool ReadAttributeValue ()
		{
			if (consumedAttribute)
				return false;
			if (NodeType == XmlNodeType.Attribute &&
					currentEntityHandling == EntityHandling.ExpandEntities) {
				consumedAttribute = true;
				return true;
			}
			else if (IsDefault) {
				consumedAttribute = true;
				return true;
			}
			else
				return reader.ReadAttributeValue ();
		}

#if NET_1_0
		public override string ReadInnerXml ()
		{
			// MS.NET 1.0 has a serious bug here. It skips validation.
			return reader.ReadInnerXml ();
		}

		public override string ReadOuterXml ()
		{
			// MS.NET 1.0 has a serious bug here. It skips validation.
			return reader.ReadOuterXml ();
		}
#endif

		public override string ReadString ()
		{
			// It seems to be the same as ReadInnerXml(). 
			return base.ReadStringInternal ();
		}

		public override void ResolveEntity ()
		{
			if (resolver == null)
				return;

			// "reader." is required since NodeType must not be entityref by nature.
			if (reader.NodeType != XmlNodeType.EntityReference)
				throw new InvalidOperationException ("The current node is not an Entity Reference");
			DTDEntityDeclaration entity = DTD != null ? DTD.EntityDecls [reader.Name] as DTDEntityDeclaration : null;

			XmlNodeType xmlReaderNodeType =
				(currentAttribute != null) ? XmlNodeType.Attribute : XmlNodeType.Element;

#if NET_2_0
			if (entity == null)
					throw NotWFError (String.Format ("Reference to undeclared entity '{0}'.", reader.Name));
#endif

			// MS.NET 1.x ignores undeclared entity reference here..
			if (entity != null && entity.SystemId != null) {
				Uri baseUri = entity.BaseURI == String.Empty ? null : new Uri (entity.BaseURI);
				Stream stream = resolver.GetEntity (resolver.ResolveUri (baseUri, entity.SystemId), null, typeof (Stream)) as Stream;
				nextEntityReader = new XmlTextReader (stream, xmlReaderNodeType, ParserContext);
			} else {
				string replacementText =
					(entity != null) ? entity.EntityValue : String.Empty;
				nextEntityReader = new XmlTextReader (replacementText, xmlReaderNodeType, ParserContext);
			}
			nextEntityReader.XmlResolver = resolver;
		}

		public override int AttributeCount {
			get {
				if (currentTextValue != null)
					return 0;

				if (dtd == null || !insideContent)
					return reader.AttributeCount;

				return attributes.Count;
			}
		}

		public override string BaseURI {
			get {
				return reader.BaseURI;
			}
		}

		public override bool CanResolveEntity {
			get { return true; }
		}

		public override int Depth {
			get {
				int baseNum = reader.Depth;
				if (entityReaderDepthStack.Count > 0) {
					baseNum += (int) entityReaderDepthStack.Peek ();
					if (NodeType != XmlNodeType.EndEntity)
						baseNum++;
				}
				if (currentTextValue != null && reader.NodeType == XmlNodeType.EndElement)
					baseNum++;

				return IsDefault ? baseNum + 1 : baseNum;
			}
		}

		public override bool EOF {
			get { return reader.EOF && entityReaderStack.Count == 0; }
		}

		public override bool HasValue {
			get {
				return IsDefault ? true :
					currentTextValue != null ? true :
					reader.HasValue; }
		}

		public override bool IsDefault {
			get {
				if (currentTextValue != null)
					return false;
				if (currentAttribute == null)
					return false;
				return reader.GetAttribute (currentAttribute) == null;
			}
		}

		public override bool IsEmptyElement {
			get {
				if (currentTextValue != null)
					return false;
				return reader.IsEmptyElement;
			}
		}

		public override string this [int i] {
			get { return GetAttribute (i); }
		}

		public override string this [string name] {
			get { return GetAttribute (name); }
		}

		public override string this [string name, string ns] {
			get { return GetAttribute (name, ns); }
		}

		public int LineNumber {
			get {
				IXmlLineInfo info = reader as IXmlLineInfo;
				return (info != null) ? info.LineNumber : 0;
			}
		}

		public int LinePosition {
			get {
				IXmlLineInfo info = reader as IXmlLineInfo;
				return (info != null) ? info.LinePosition : 0;
			}
		}

		public override string LocalName {
			get {
				if (currentTextValue != null || consumedAttribute)
					return String.Empty;
				if (entityReaderStack.Count > 0 && reader.EOF)
					return ((XmlReader) entityReaderStack.Peek ()).LocalName; // name of EndEntity
				else if (NodeType == XmlNodeType.Attribute)
					return (string) attributeLocalNames [currentAttribute];
				else
					return reader.LocalName;
			}
		}

		public override string Name {
			get {
				if (currentTextValue != null || consumedAttribute)
					return String.Empty;
				if (entityReaderStack.Count > 0 && reader.EOF)
					return ((XmlReader) entityReaderStack.Peek ()).Name; // name of EndEntity
				else if (NodeType == XmlNodeType.Attribute)
					return currentAttribute;
				else
					return reader.Name;
			}
		}

		public override string NamespaceURI {
			get {
				if (currentTextValue != null || consumedAttribute)
					return String.Empty;
				switch (NodeType) {
				case XmlNodeType.Attribute:
					return (string) attributeNamespaces [currentAttribute];
				case XmlNodeType.Element:
				case XmlNodeType.EndElement:
					return nsmgr.LookupNamespace (Prefix);
				default:
					return String.Empty;
				}
			}
		}

		public override XmlNameTable NameTable {
			get { return reader.NameTable; }
		}

		public override XmlNodeType NodeType {
			get {
				if (currentTextValue != null)
					return isSignificantWhitespace ? XmlNodeType.SignificantWhitespace :
						isWhitespace ? XmlNodeType.Whitespace :
						XmlNodeType.Text;

				if (entityReaderStack.Count > 0 && reader.EOF)
					return XmlNodeType.EndEntity;

				// If consumedAttribute is true, then entities must be resolved.
				return consumedAttribute ? XmlNodeType.Text :
					IsDefault ? XmlNodeType.Attribute :
					reader.NodeType;
			}
		}

		public XmlParserContext ParserContext {
			get { return XmlSchemaUtil.GetParserContext (reader); }
		}

		public override string Prefix {
			get {
				if (currentTextValue != null || consumedAttribute)
					return String.Empty;
				else if (NodeType == XmlNodeType.Attribute)
					return (string) attributePrefixes [currentAttribute];
				else
					return reader.Prefix;
			}
		}
		
		public override char QuoteChar {
			get {
				// If it is not actually on an attribute, then it returns
				// undefined value or '"'.
				return reader.QuoteChar;
			}
		}

		public override ReadState ReadState {
			get {
				if (reader.ReadState == ReadState.EndOfFile && currentTextValue != null)
					return ReadState.Interactive;
				return reader.ReadState;
			}
		}

		public object SchemaType {
			get {
				if (currentElement == null)
					return null;
				DTDAttListDeclaration decl =
					DTD.AttListDecls [currentElement];
				DTDAttributeDefinition def =
					decl != null ? decl [currentAttribute] : null;
				return def != null ? def.Datatype : null;
			}
		}

		char [] whitespaceChars = new char [] {' '};
		private string FilterNormalization (string attrName, string rawValue)
		{
			if (DTD == null || NodeType != XmlNodeType.Attribute ||
				sourceTextReader == null ||
				!sourceTextReader.Normalization)
				return rawValue;

			DTDAttributeDefinition def = 
				dtd.AttListDecls [currentElement].Get (attrName);
			valueBuilder.Append (rawValue);
			valueBuilder.Replace ('\r', ' ');
			valueBuilder.Replace ('\n', ' ');
			valueBuilder.Replace ('\t', ' ');
			try {
				if (def.Datatype.TokenizedType == XmlTokenizedType.CDATA)
					return valueBuilder.ToString ();
				
				for (int i=0; i < valueBuilder.Length; i++) {
					if (valueBuilder [i] != ' ')
						continue;
					while (++i < valueBuilder.Length && valueBuilder [i] == ' ')
						valueBuilder.Remove (i, 1);
				}
				return valueBuilder.ToString ().Trim (whitespaceChars);
			} finally {
				valueBuilder.Length = 0;
			}
		}

		public override string Value {
			get {
				if (currentTextValue != null)
					return currentTextValue;
				// As to this property, MS.NET seems ignorant of EntityHandling...
				else if (NodeType == XmlNodeType.Attribute
					// It also covers default attribute text.
 					|| consumedAttribute)
					return FilterNormalization (Name, (string) attributeValues [currentAttribute]);
				else
					return FilterNormalization (Name, reader.Value);
			}
		}

		public override string XmlLang {
			get {
				string val = this ["xml:lang"];
				return val != null ? val : reader.XmlLang;
			}
		}

		public XmlResolver XmlResolver {
			set {
				resolver = value;
			}
		}

		public override XmlSpace XmlSpace {
			get {
				string val = this ["xml:space"];
				switch (val) {
				case "preserve":
					return XmlSpace.Preserve;
				case "default":
					return XmlSpace.Default;
				default:
					return reader.XmlSpace;
				}
			}
		}

	}
}