DTDValidatingReader.cs 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072
  1. using System;
  2. using System.Collections.Specialized;
  3. using System.Collections;
  4. using System.IO;
  5. using System.Text;
  6. using System.Xml;
  7. using System.Xml.Schema;
  8. namespace Mono.Xml
  9. {
  10. public class DTDValidatingReader : XmlReader, IXmlLineInfo, IHasXmlParserContext, IHasXmlSchemaInfo
  11. {
  12. public DTDValidatingReader (XmlReader reader)
  13. : this (reader, null)
  14. {
  15. }
  16. public DTDValidatingReader (XmlReader reader,
  17. XmlValidatingReader validatingReader)
  18. {
  19. entityReaderStack = new Stack ();
  20. entityReaderNameStack = new Stack ();
  21. entityReaderDepthStack = new Stack ();
  22. this.reader = reader;
  23. this.sourceTextReader = reader as XmlTextReader;
  24. elementStack = new Stack ();
  25. automataStack = new Stack ();
  26. attributes = new StringCollection ();
  27. attributeValues = new NameValueCollection ();
  28. attributeLocalNames = new NameValueCollection ();
  29. attributeNamespaces = new NameValueCollection ();
  30. this.validatingReader = validatingReader;
  31. valueBuilder = new StringBuilder ();
  32. idList = new ArrayList ();
  33. missingIDReferences = new ArrayList ();
  34. resolver = new XmlUrlResolver ();
  35. }
  36. Stack entityReaderStack;
  37. Stack entityReaderNameStack;
  38. Stack entityReaderDepthStack;
  39. XmlReader reader;
  40. XmlTextReader sourceTextReader;
  41. XmlTextReader nextEntityReader;
  42. DTDObjectModel dtd;
  43. Stack elementStack;
  44. Stack automataStack;
  45. string currentElement;
  46. string currentAttribute;
  47. string currentTextValue;
  48. string constructingTextValue;
  49. bool shouldResetCurrentTextValue;
  50. bool consumedAttribute;
  51. bool insideContent;
  52. DTDAutomata currentAutomata;
  53. DTDAutomata previousAutomata;
  54. bool isStandalone;
  55. StringCollection attributes;
  56. NameValueCollection attributeValues;
  57. NameValueCollection attributeLocalNames;
  58. NameValueCollection attributeNamespaces;
  59. StringBuilder valueBuilder;
  60. ArrayList idList;
  61. ArrayList missingIDReferences;
  62. XmlResolver resolver;
  63. EntityHandling currentEntityHandling;
  64. bool isSignificantWhitespace;
  65. bool isWhitespace;
  66. bool isText;
  67. bool nextMaybeSignificantWhitespace;
  68. // This field is used to get properties and to raise events.
  69. XmlValidatingReader validatingReader;
  70. public DTDObjectModel DTD {
  71. get { return dtd; }
  72. }
  73. public override void Close ()
  74. {
  75. reader.Close ();
  76. }
  77. // We had already done attribute validation, so can ignore name.
  78. public override string GetAttribute (int i)
  79. {
  80. if (currentTextValue != null)
  81. throw new IndexOutOfRangeException ("Specified index is out of range: " + i);
  82. if (dtd == null)
  83. return reader.GetAttribute (i);
  84. if (attributes.Count <= i)
  85. throw new IndexOutOfRangeException ("Specified index is out of range: " + i);
  86. return FilterNormalization (attributes [i], attributeValues [i]);
  87. }
  88. public override string GetAttribute (string name)
  89. {
  90. if (currentTextValue != null)
  91. return null;
  92. if (dtd == null)
  93. return reader.GetAttribute (name);
  94. return FilterNormalization (name, attributeValues [name]);
  95. }
  96. public override string GetAttribute (string name, string ns)
  97. {
  98. if (currentTextValue != null)
  99. return null;
  100. if (dtd == null)
  101. return reader.GetAttribute (name, ns);
  102. return reader.GetAttribute (attributeLocalNames [name], ns);
  103. }
  104. bool IXmlLineInfo.HasLineInfo ()
  105. {
  106. IXmlLineInfo ixli = reader as IXmlLineInfo;
  107. if (ixli != null)
  108. return ixli.HasLineInfo ();
  109. else
  110. return false;
  111. }
  112. public override string LookupNamespace (string prefix)
  113. {
  114. // Does it mean anything with DTD?
  115. return reader.LookupNamespace (prefix);
  116. }
  117. public override void MoveToAttribute (int i)
  118. {
  119. if (currentTextValue != null)
  120. throw new IndexOutOfRangeException ("The index is out of range.");
  121. if (dtd == null) {
  122. reader.MoveToAttribute (i);
  123. currentAttribute = reader.Name;
  124. consumedAttribute = false;
  125. return;
  126. }
  127. if (currentElement == null)
  128. return;
  129. if (attributes.Count > i) {
  130. currentAttribute = attributes [i];
  131. consumedAttribute = false;
  132. return;
  133. } else
  134. throw new IndexOutOfRangeException ("The index is out of range.");
  135. }
  136. public override bool MoveToAttribute (string name)
  137. {
  138. if (currentTextValue != null)
  139. return false;
  140. if (dtd == null) {
  141. bool b = reader.MoveToAttribute (name);
  142. if (b) {
  143. currentAttribute = reader.Name;
  144. consumedAttribute = false;
  145. }
  146. return b;
  147. }
  148. if (currentElement == null)
  149. return false;
  150. int idx = attributes.IndexOf (name);
  151. if (idx >= 0) {
  152. currentAttribute = name;
  153. consumedAttribute = false;
  154. return true;
  155. }
  156. return false;
  157. }
  158. public override bool MoveToAttribute (string name, string ns)
  159. {
  160. if (currentTextValue != null)
  161. return false;
  162. if (dtd == null) {
  163. bool b = reader.MoveToAttribute (name, ns);
  164. if (b) {
  165. currentAttribute = reader.Name;
  166. consumedAttribute = false;
  167. }
  168. return b;
  169. }
  170. if (reader.MoveToAttribute (name, ns)) {
  171. currentAttribute = reader.Name;
  172. consumedAttribute = false;
  173. return true;
  174. }
  175. foreach (string iter in attributes)
  176. if (attributeLocalNames [iter] == name)
  177. return MoveToAttribute (iter);
  178. return false;
  179. }
  180. public override bool MoveToElement ()
  181. {
  182. if (currentTextValue != null)
  183. return false;
  184. bool b = reader.MoveToElement ();
  185. if (!b)
  186. return false;
  187. currentAttribute = null;
  188. consumedAttribute = false;
  189. return true;
  190. }
  191. public override bool MoveToFirstAttribute ()
  192. {
  193. if (currentTextValue != null)
  194. return false;
  195. if (dtd == null) {
  196. bool b = reader.MoveToFirstAttribute ();
  197. if (b) {
  198. currentAttribute = reader.Name;
  199. consumedAttribute = false;
  200. }
  201. return b;
  202. }
  203. if (attributes.Count == 0)
  204. return false;
  205. currentAttribute = attributes [0];
  206. reader.MoveToAttribute (currentAttribute);
  207. consumedAttribute = false;
  208. return true;
  209. }
  210. public override bool MoveToNextAttribute ()
  211. {
  212. if (currentTextValue != null)
  213. return false;
  214. if (dtd == null) {
  215. bool b = reader.MoveToNextAttribute ();
  216. if (b) {
  217. currentAttribute = reader.Name;
  218. consumedAttribute = false;
  219. }
  220. return b;
  221. }
  222. if (currentAttribute == null)
  223. return MoveToFirstAttribute ();
  224. int idx = attributes.IndexOf (currentAttribute);
  225. if (idx + 1 < attributes.Count) {
  226. currentAttribute = attributes [idx + 1];
  227. reader.MoveToAttribute (currentAttribute);
  228. consumedAttribute = false;
  229. return true;
  230. } else
  231. return false;
  232. }
  233. public override bool Read ()
  234. {
  235. if (currentTextValue != null)
  236. shouldResetCurrentTextValue = true;
  237. MoveToElement ();
  238. currentElement = null;
  239. currentAttribute = null;
  240. consumedAttribute = false;
  241. attributes.Clear ();
  242. attributeValues.Clear ();
  243. attributeNamespaces.Clear ();
  244. isWhitespace = false;
  245. isSignificantWhitespace = false;
  246. isText = false;
  247. nextMaybeSignificantWhitespace = false;
  248. bool b = ReadContent () || currentTextValue != null;
  249. if (!b && this.missingIDReferences.Count > 0) {
  250. this.HandleError ("Missing ID reference was found: " +
  251. String.Join (",", missingIDReferences.ToArray (typeof (string)) as string []),
  252. XmlSeverityType.Error);
  253. // Don't output the same errors so many times.
  254. this.missingIDReferences.Clear ();
  255. }
  256. currentEntityHandling = validatingReader.EntityHandling;
  257. return b;
  258. }
  259. private bool ReadContent ()
  260. {
  261. if (nextEntityReader != null) {
  262. if (DTD == null || DTD.EntityDecls [reader.Name] == null)
  263. throw new XmlException ("Entity '" + reader.Name + "' was not declared.");
  264. entityReaderStack.Push (reader);
  265. entityReaderNameStack.Push (reader.Name);
  266. entityReaderDepthStack.Push (Depth);
  267. reader = sourceTextReader = nextEntityReader;
  268. nextEntityReader = null;
  269. return ReadContent ();
  270. } else if (reader.EOF && entityReaderStack.Count > 0) {
  271. reader = entityReaderStack.Pop () as XmlReader;
  272. entityReaderNameStack.Pop ();
  273. entityReaderDepthStack.Pop ();
  274. sourceTextReader = reader as XmlTextReader;
  275. return ReadContent ();
  276. }
  277. bool b = !reader.EOF;
  278. if (shouldResetCurrentTextValue) {
  279. currentTextValue = null;
  280. shouldResetCurrentTextValue = false;
  281. }
  282. else
  283. b = reader.Read ();
  284. if (!insideContent && reader.NodeType == XmlNodeType.Element) {
  285. insideContent = true;
  286. if (dtd == null)
  287. currentAutomata = null;
  288. else
  289. currentAutomata = dtd.RootAutomata;
  290. }
  291. if (!b) {
  292. if (entityReaderStack.Count > 0) {
  293. if (validatingReader.EntityHandling == EntityHandling.ExpandEntities)
  294. return ReadContent ();
  295. else
  296. return true; // EndEntity
  297. }
  298. if (elementStack.Count != 0)
  299. throw new InvalidOperationException ("Unexpected end of XmlReader.");
  300. return false;
  301. }
  302. bool dontResetTextType = false;
  303. switch (reader.NodeType) {
  304. case XmlNodeType.XmlDeclaration:
  305. if (GetAttribute ("standalone") == "yes")
  306. isStandalone = true;
  307. break;
  308. case XmlNodeType.DocumentType:
  309. XmlTextReader xmlTextReader = reader as XmlTextReader;
  310. if (xmlTextReader == null) {
  311. xmlTextReader = new XmlTextReader ("", XmlNodeType.Document, null);
  312. xmlTextReader.XmlResolver = resolver;
  313. xmlTextReader.GenerateDTDObjectModel (reader.Name,
  314. reader ["PUBLIC"], reader ["SYSTEM"], reader.Value);
  315. }
  316. this.dtd = xmlTextReader.DTD;
  317. // Validity Constraints Check.
  318. if (DTD.Errors.Length > 0)
  319. foreach (XmlSchemaException ex in DTD.Errors)
  320. HandleError (ex.Message, XmlSeverityType.Error);
  321. // NData target exists.
  322. foreach (DTDEntityDeclaration ent in dtd.EntityDecls.Values)
  323. if (ent.NotationName != null && dtd.NotationDecls [ent.NotationName] == null)
  324. this.HandleError ("Target notation was not found for NData in entity declaration " + ent.Name + ".",
  325. XmlSeverityType.Error);
  326. // NOTATION exists for attribute default values
  327. foreach (DTDAttListDeclaration attListIter in dtd.AttListDecls.Values)
  328. foreach (DTDAttributeDefinition def in attListIter.Definitions)
  329. if (def.Datatype.TokenizedType == XmlTokenizedType.NOTATION) {
  330. foreach (string notation in def.EnumeratedNotations)
  331. if (dtd.NotationDecls [notation] == null)
  332. this.HandleError ("Target notation was not found for NOTATION typed attribute default " + def.Name + ".",
  333. XmlSeverityType.Error);
  334. }
  335. break;
  336. case XmlNodeType.Element:
  337. if (constructingTextValue != null) {
  338. currentTextValue = constructingTextValue;
  339. constructingTextValue = null;
  340. return true;
  341. }
  342. elementStack.Push (reader.Name);
  343. // startElementDeriv
  344. // If no schema specification, then skip validation.
  345. if (currentAutomata == null) {
  346. SetupValidityIgnorantAttributes ();
  347. if (reader.IsEmptyElement)
  348. goto case XmlNodeType.EndElement;
  349. break;
  350. }
  351. previousAutomata = currentAutomata;
  352. currentAutomata = currentAutomata.TryStartElement (reader.Name);
  353. if (currentAutomata == DTD.Invalid) {
  354. HandleError (String.Format ("Invalid start element found: {0}", reader.Name),
  355. XmlSeverityType.Error);
  356. currentAutomata = previousAutomata;
  357. }
  358. DTDElementDeclaration decl = DTD.ElementDecls [reader.Name];
  359. if (decl == null) {
  360. HandleError (String.Format ("Element {0} is not declared.", reader.Name),
  361. XmlSeverityType.Error);
  362. currentAutomata = previousAutomata;
  363. }
  364. currentElement = Name;
  365. automataStack.Push (currentAutomata);
  366. if (decl != null) // i.e. not invalid
  367. currentAutomata = decl.ContentModel.GetAutomata ();
  368. DTDAttListDeclaration attList = dtd.AttListDecls [currentElement];
  369. if (attList != null) {
  370. // check attributes
  371. ValidateAttributes (attList);
  372. currentAttribute = null;
  373. } else {
  374. if (reader.HasAttributes) {
  375. HandleError (String.Format (
  376. "Attributes are found on element {0} while it has no attribute definitions.", currentElement),
  377. XmlSeverityType.Error);
  378. }
  379. SetupValidityIgnorantAttributes ();
  380. }
  381. // If it is empty element then directly check end element.
  382. if (reader.IsEmptyElement)
  383. goto case XmlNodeType.EndElement;
  384. break;
  385. case XmlNodeType.EndElement:
  386. if (constructingTextValue != null) {
  387. currentTextValue = constructingTextValue;
  388. constructingTextValue = null;
  389. return true;
  390. }
  391. elementStack.Pop ();
  392. // endElementDeriv
  393. // If no schema specification, then skip validation.
  394. if (currentAutomata == null)
  395. break;
  396. decl = DTD.ElementDecls [reader.Name];
  397. if (decl == null) {
  398. HandleError (String.Format ("Element {0} is not declared.", reader.Name),
  399. XmlSeverityType.Error);
  400. }
  401. previousAutomata = currentAutomata;
  402. // Don't let currentAutomata
  403. DTDAutomata tmpAutomata = currentAutomata.TryEndElement ();
  404. if (tmpAutomata == DTD.Invalid) {
  405. HandleError (String.Format ("Invalid end element found: {0}", reader.Name),
  406. XmlSeverityType.Error);
  407. currentAutomata = previousAutomata;
  408. }
  409. currentAutomata = automataStack.Pop () as DTDAutomata;
  410. break;
  411. case XmlNodeType.CDATA:
  412. if (currentTextValue != null) {
  413. currentTextValue = constructingTextValue;
  414. constructingTextValue = null;
  415. return true;
  416. }
  417. goto case XmlNodeType.Text;
  418. case XmlNodeType.SignificantWhitespace:
  419. if (!isText)
  420. isSignificantWhitespace = true;
  421. dontResetTextType = true;
  422. goto case XmlNodeType.Text;
  423. case XmlNodeType.Text:
  424. isText = true;
  425. if (!dontResetTextType) {
  426. isWhitespace = isSignificantWhitespace = false;
  427. }
  428. // If no schema specification, then skip validation.
  429. if (currentAutomata == null)
  430. break;
  431. DTDElementDeclaration elem = dtd.ElementDecls [elementStack.Peek () as string];
  432. // Here element should have been already validated, so
  433. // if no matching declaration is found, simply ignore.
  434. if (elem != null && !elem.IsMixedContent && !elem.IsAny) {
  435. HandleError (String.Format ("Current element {0} does not allow character data content.", elementStack.Peek () as string),
  436. XmlSeverityType.Error);
  437. currentAutomata = previousAutomata;
  438. }
  439. if (validatingReader.EntityHandling == EntityHandling.ExpandEntities) {
  440. constructingTextValue += reader.Value;
  441. return ReadContent ();
  442. }
  443. break;
  444. case XmlNodeType.Whitespace:
  445. if (nextMaybeSignificantWhitespace) {
  446. currentTextValue = reader.Value;
  447. nextMaybeSignificantWhitespace = false;
  448. goto case XmlNodeType.SignificantWhitespace;
  449. }
  450. if (!isText && !isSignificantWhitespace)
  451. isWhitespace = true;
  452. if (validatingReader.EntityHandling == EntityHandling.ExpandEntities) {
  453. constructingTextValue += reader.Value;
  454. return ReadContent ();
  455. }
  456. break;
  457. case XmlNodeType.EntityReference:
  458. if (validatingReader.EntityHandling == EntityHandling.ExpandEntities) {
  459. ResolveEntity ();
  460. return ReadContent ();
  461. }
  462. break;
  463. }
  464. MoveToElement ();
  465. return true;
  466. }
  467. private void SetupValidityIgnorantAttributes ()
  468. {
  469. if (reader.MoveToFirstAttribute ()) {
  470. // If it was invalid, simply add specified attributes.
  471. do {
  472. attributes.Add (reader.Name);
  473. attributeLocalNames.Add (reader.Name, reader.LocalName);
  474. attributeNamespaces.Add (reader.Name, reader.NamespaceURI);
  475. attributeValues.Add (reader.Name, reader.Value);
  476. } while (reader.MoveToNextAttribute ());
  477. reader.MoveToElement ();
  478. }
  479. }
  480. private void HandleError (string message, XmlSeverityType severity)
  481. {
  482. if (validatingReader != null &&
  483. validatingReader.ValidationType == ValidationType.None)
  484. return;
  485. IXmlLineInfo info = this as IXmlLineInfo;
  486. bool hasLine = info.HasLineInfo ();
  487. XmlSchemaException ex = new XmlSchemaException (
  488. message,
  489. hasLine ? info.LineNumber : 0,
  490. hasLine ? info.LinePosition : 0,
  491. null,
  492. BaseURI,
  493. null);
  494. if (validatingReader != null)
  495. this.validatingReader.OnValidationEvent (this,
  496. new ValidationEventArgs (ex, ex.Message, severity));
  497. else
  498. throw ex;
  499. }
  500. Stack attributeValueEntityStack = new Stack ();
  501. private void ValidateAttributes (DTDAttListDeclaration decl)
  502. {
  503. while (reader.MoveToNextAttribute ()) {
  504. string attrName = reader.Name;
  505. this.currentAttribute = attrName;
  506. attributes.Add (attrName);
  507. attributeLocalNames.Add (attrName, reader.LocalName);
  508. attributeNamespaces.Add (attrName, reader.NamespaceURI);
  509. bool hasError = false;
  510. XmlReader targetReader = reader;
  511. while (attributeValueEntityStack.Count >= 0) {
  512. if (!targetReader.ReadAttributeValue ()) {
  513. if (attributeValueEntityStack.Count > 0) {
  514. targetReader = attributeValueEntityStack.Pop () as XmlReader;
  515. continue;
  516. } else
  517. break;
  518. }
  519. switch (targetReader.NodeType) {
  520. case XmlNodeType.EntityReference:
  521. DTDEntityDeclaration edecl = DTD.EntityDecls [targetReader.Name];
  522. if (edecl == null) {
  523. HandleError (String.Format ("Referenced entity {0} is not declared.", targetReader.Name),
  524. XmlSeverityType.Error);
  525. hasError = true;
  526. } else {
  527. XmlTextReader etr = new XmlTextReader (edecl.EntityValue, XmlNodeType.Attribute, ParserContext);
  528. attributeValueEntityStack.Push (targetReader);
  529. targetReader = etr;
  530. continue;
  531. }
  532. break;
  533. case XmlNodeType.EndEntity:
  534. break;
  535. default:
  536. valueBuilder.Append (targetReader.Value);
  537. break;
  538. }
  539. }
  540. reader.MoveToElement ();
  541. reader.MoveToAttribute (attrName);
  542. string attrValue = valueBuilder.ToString ();
  543. valueBuilder.Length = 0;
  544. attributeValues.Add (attrName, attrValue);
  545. DTDAttributeDefinition def = decl [reader.Name];
  546. if (def == null) {
  547. HandleError (String.Format ("Attribute {0} is not declared.", reader.Name),
  548. XmlSeverityType.Error);
  549. } else {
  550. // check enumeration constraint
  551. if (def.EnumeratedAttributeDeclaration.Count > 0)
  552. if (!def.EnumeratedAttributeDeclaration.Contains (
  553. FilterNormalization (reader.Name, attrValue)))
  554. HandleError (String.Format ("Attribute enumeration constraint error in attribute {0}, value {1}.",
  555. reader.Name, attrValue), XmlSeverityType.Error);
  556. if (def.EnumeratedNotations.Count > 0)
  557. if (!def.EnumeratedNotations.Contains (
  558. FilterNormalization (reader.Name, attrValue)))
  559. HandleError (String.Format ("Attribute notation enumeration constraint error in attribute {0}, value {1}.",
  560. reader.Name, attrValue), XmlSeverityType.Error);
  561. // check type constraint
  562. string normalized = null;
  563. if (def.Datatype != null)
  564. normalized = FilterNormalization (def.Name, attrValue);
  565. else
  566. normalized = attrValue;
  567. switch (def.Datatype.TokenizedType) {
  568. case XmlTokenizedType.ID:
  569. if (!XmlChar.IsName (normalized))
  570. HandleError (String.Format ("ID attribute value must match the creation rule Name: {0}", attrValue),
  571. XmlSeverityType.Error);
  572. else if (this.idList.Contains (normalized)) {
  573. HandleError (String.Format ("Node with ID {0} was already appeared.", attrValue),
  574. XmlSeverityType.Error);
  575. } else {
  576. if (missingIDReferences.Contains (normalized))
  577. missingIDReferences.Remove (normalized);
  578. idList.Add (normalized);
  579. }
  580. break;
  581. case XmlTokenizedType.IDREF:
  582. if (!XmlChar.IsName (normalized))
  583. HandleError (String.Format ("IDREF attribute value must match the creation rule Name: {0}", attrValue),
  584. XmlSeverityType.Error);
  585. if (!idList.Contains (normalized))
  586. missingIDReferences.Add (normalized);
  587. break;
  588. case XmlTokenizedType.IDREFS:
  589. string [] idrefs = def.Datatype.ParseValue (normalized, NameTable, null) as string [];
  590. foreach (string idref in idrefs) {
  591. string each = FilterNormalization (def.Name, idref);
  592. if (!XmlChar.IsName (each))
  593. HandleError (String.Format ("Each ID in IDREFS attribute value must match the creation rule Name: {0}", attrValue),
  594. XmlSeverityType.Error);
  595. if (!idList.Contains (each))
  596. missingIDReferences.Add (each);
  597. }
  598. break;
  599. case XmlTokenizedType.ENTITY:
  600. if (dtd.EntityDecls [normalized] == null)
  601. HandleError (String.Format ("Reference to undeclared entity was found in attribute {0}.", reader.Name),
  602. XmlSeverityType.Error);
  603. break;
  604. case XmlTokenizedType.ENTITIES:
  605. string [] entrefs = def.Datatype.ParseValue (normalized, NameTable, null) as string [];
  606. foreach (string entref in entrefs) {
  607. if (dtd.EntityDecls [ FilterNormalization (reader.Name, entref) ] == null)
  608. HandleError (String.Format ("Reference to undeclared entity was found in attribute {0}.", reader.Name),
  609. XmlSeverityType.Error);
  610. }
  611. break;
  612. case XmlTokenizedType.NMTOKEN:
  613. if (!XmlChar.IsNmToken (normalized))
  614. HandleError (String.Format ("NMTOKEN attribute value must match the creation rule NMTOKEN. Name={0}", reader.Name),
  615. XmlSeverityType.Error);
  616. break;
  617. case XmlTokenizedType.NMTOKENS:
  618. string [] tokens = def.Datatype.ParseValue (normalized, NameTable, null) as string [];
  619. foreach (string token in tokens)
  620. if (!XmlChar.IsNmToken (FilterNormalization (def.Name, token)))
  621. HandleError (String.Format ("Name Token in NMTOKENS attribute value must match the creation rule NMTOKEN. Name={0}", reader.Name),
  622. XmlSeverityType.Error);
  623. break;
  624. }
  625. if (isStandalone && !def.IsInternalSubset && attrValue != normalized)
  626. HandleError ("In standalone document, attribute value characters must not be checked against external definition.", XmlSeverityType.Error);
  627. if (def.OccurenceType == DTDAttributeOccurenceType.Fixed &&
  628. attrValue != def.DefaultValue) {
  629. HandleError (String.Format ("Fixed attribute {0} in element {1} has invalid value {2}.",
  630. def.Name, decl.Name, attrValue),
  631. XmlSeverityType.Error);
  632. }
  633. }
  634. }
  635. // Check if all required attributes exist, and/or
  636. // if there is default values, then add them.
  637. foreach (DTDAttributeDefinition def in decl.Definitions)
  638. if (!attributes.Contains (def.Name)) {
  639. if (def.OccurenceType == DTDAttributeOccurenceType.Required) {
  640. HandleError (String.Format ("Required attribute {0} in element {1} not found .",
  641. def.Name, decl.Name),
  642. XmlSeverityType.Error);
  643. }
  644. else if (def.DefaultValue != null) {
  645. if (this.isStandalone && !def.IsInternalSubset)
  646. HandleError ("In standalone document, external default value definition must not be applied.", XmlSeverityType.Error);
  647. switch (validatingReader.ValidationType) {
  648. case ValidationType.Auto:
  649. if (validatingReader.Schemas.Count == 0)
  650. goto case ValidationType.DTD;
  651. break;
  652. case ValidationType.DTD:
  653. case ValidationType.None:
  654. // Other than them, ignore DTD defaults.
  655. attributes.Add (def.Name);
  656. int colonAt = def.Name.IndexOf (':');
  657. attributeLocalNames.Add (def.Name, colonAt < 0 ? def.Name : def.Name.Substring (colonAt + 1));
  658. attributeNamespaces.Add (def.Name, colonAt < 0 ? def.Name : def.Name.Substring (0, colonAt));
  659. attributeValues.Add (def.Name, def.DefaultValue);
  660. break;
  661. }
  662. }
  663. }
  664. reader.MoveToElement ();
  665. }
  666. public override bool ReadAttributeValue ()
  667. {
  668. if (consumedAttribute)
  669. return false;
  670. if (NodeType == XmlNodeType.Attribute &&
  671. currentEntityHandling == EntityHandling.ExpandEntities) {
  672. consumedAttribute = true;
  673. return true;
  674. }
  675. else if (IsDefault) {
  676. consumedAttribute = true;
  677. return true;
  678. }
  679. else
  680. return reader.ReadAttributeValue ();
  681. }
  682. #if NET_1_0
  683. public override string ReadInnerXml ()
  684. {
  685. // MS.NET 1.0 has a serious bug here. It skips validation.
  686. return reader.ReadInnerXml ();
  687. }
  688. public override string ReadOuterXml ()
  689. {
  690. // MS.NET 1.0 has a serious bug here. It skips validation.
  691. return reader.ReadOuterXml ();
  692. }
  693. #endif
  694. public override string ReadString ()
  695. {
  696. // It seems to be the same as ReadInnerXml().
  697. return base.ReadStringInternal ();
  698. }
  699. public override void ResolveEntity ()
  700. {
  701. if (resolver == null)
  702. return;
  703. // "reader." is required since NodeType must not be entityref by nature.
  704. if (reader.NodeType != XmlNodeType.EntityReference)
  705. throw new InvalidOperationException ("The current node is not an Entity Reference");
  706. DTDEntityDeclaration entity = DTD != null ? DTD.EntityDecls [reader.Name] as DTDEntityDeclaration : null;
  707. XmlNodeType xmlReaderNodeType =
  708. (currentAttribute != null) ? XmlNodeType.Attribute : XmlNodeType.Element;
  709. // MS.NET seems simply ignoring undeclared entity reference here ;-(
  710. if (entity != null && entity.SystemId != null) {
  711. Uri baseUri = entity.BaseURI == null ? null : new Uri (entity.BaseURI);
  712. Stream stream = resolver.GetEntity (resolver.ResolveUri (baseUri, entity.SystemId), null, typeof (Stream)) as Stream;
  713. nextEntityReader = new XmlTextReader (stream, xmlReaderNodeType, ParserContext);
  714. } else {
  715. string replacementText =
  716. (entity != null) ? entity.EntityValue : String.Empty;
  717. nextEntityReader = new XmlTextReader (replacementText, xmlReaderNodeType, ParserContext);
  718. }
  719. nextEntityReader.XmlResolver = resolver;
  720. nextEntityReader.SkipTextDeclaration ();
  721. }
  722. public override int AttributeCount {
  723. get {
  724. if (currentTextValue != null)
  725. return 0;
  726. if (dtd == null || !insideContent)
  727. return reader.AttributeCount;
  728. return attributes.Count;
  729. }
  730. }
  731. public override string BaseURI {
  732. get {
  733. return reader.BaseURI;
  734. }
  735. }
  736. public override bool CanResolveEntity {
  737. get { return true; }
  738. }
  739. public override int Depth {
  740. get {
  741. int baseNum = reader.Depth;
  742. if (entityReaderDepthStack.Count > 0) {
  743. baseNum += (int) entityReaderDepthStack.Peek ();
  744. if (NodeType != XmlNodeType.EndEntity)
  745. baseNum++;
  746. }
  747. if (currentTextValue != null && reader.NodeType == XmlNodeType.EndElement)
  748. baseNum++;
  749. return IsDefault ? baseNum + 1 : baseNum;
  750. }
  751. }
  752. public override bool EOF {
  753. get { return reader.EOF && entityReaderStack.Count == 0; }
  754. }
  755. public override bool HasValue {
  756. get {
  757. return IsDefault ? true :
  758. currentTextValue != null ? true :
  759. reader.HasValue; }
  760. }
  761. public override bool IsDefault {
  762. get {
  763. if (currentTextValue != null)
  764. return false;
  765. if (currentAttribute == null)
  766. return false;
  767. return reader.GetAttribute (currentAttribute) == null;
  768. }
  769. }
  770. public override bool IsEmptyElement {
  771. get {
  772. if (currentTextValue != null)
  773. return false;
  774. return reader.IsEmptyElement;
  775. }
  776. }
  777. public override string this [int i] {
  778. get { return GetAttribute (i); }
  779. }
  780. public override string this [string name] {
  781. get { return GetAttribute (name); }
  782. }
  783. public override string this [string name, string ns] {
  784. get { return GetAttribute (name, ns); }
  785. }
  786. public int LineNumber {
  787. get {
  788. IXmlLineInfo info = reader as IXmlLineInfo;
  789. return (info != null) ? info.LineNumber : 0;
  790. }
  791. }
  792. public int LinePosition {
  793. get {
  794. IXmlLineInfo info = reader as IXmlLineInfo;
  795. return (info != null) ? info.LinePosition : 0;
  796. }
  797. }
  798. public override string LocalName {
  799. get {
  800. if (currentTextValue != null)
  801. return String.Empty;
  802. return IsDefault ?
  803. consumedAttribute ? String.Empty : currentAttribute :
  804. reader.LocalName;
  805. }
  806. }
  807. public override string Name {
  808. get {
  809. if (currentTextValue != null)
  810. return String.Empty;
  811. return IsDefault ?
  812. consumedAttribute ? String.Empty : currentAttribute :
  813. reader.Name;
  814. }
  815. }
  816. public override string NamespaceURI {
  817. get {
  818. if (currentTextValue != null)
  819. return String.Empty;
  820. return IsDefault ?
  821. consumedAttribute ? String.Empty : String.Empty :
  822. reader.NamespaceURI;
  823. }
  824. }
  825. public override XmlNameTable NameTable {
  826. get { return reader.NameTable; }
  827. }
  828. public override XmlNodeType NodeType {
  829. get {
  830. if (currentTextValue != null)
  831. return isSignificantWhitespace ? XmlNodeType.SignificantWhitespace :
  832. isWhitespace ? XmlNodeType.Whitespace :
  833. XmlNodeType.Text;
  834. if (entityReaderStack.Count > 0 && reader.EOF)
  835. return XmlNodeType.EndEntity;
  836. // If consumedAttribute is true, then entities must be resolved.
  837. return consumedAttribute ? XmlNodeType.Text :
  838. IsDefault ? XmlNodeType.Attribute :
  839. reader.NodeType;
  840. }
  841. }
  842. public XmlParserContext ParserContext {
  843. get { return XmlSchemaUtil.GetParserContext (reader); }
  844. }
  845. public override string Prefix {
  846. get {
  847. if (currentTextValue != null)
  848. return String.Empty;
  849. if (currentAttribute != null && NodeType != XmlNodeType.Attribute)
  850. return String.Empty;
  851. return IsDefault ? String.Empty : reader.Prefix;
  852. }
  853. }
  854. public override char QuoteChar {
  855. get {
  856. // If it is not actually on an attribute, then it returns
  857. // undefined value or '"'.
  858. return reader.QuoteChar;
  859. }
  860. }
  861. public override ReadState ReadState {
  862. get {
  863. if (reader.ReadState == ReadState.EndOfFile && currentTextValue != null)
  864. return ReadState.Interactive;
  865. return reader.ReadState;
  866. }
  867. }
  868. public object SchemaType {
  869. get {
  870. if (currentElement == null)
  871. return null;
  872. DTDAttributeDefinition def =
  873. DTD.AttListDecls [currentElement] [currentAttribute];
  874. return def.Datatype;
  875. }
  876. }
  877. char [] whitespaceChars = new char [] {' '};
  878. private string FilterNormalization (string attrName, string rawValue)
  879. {
  880. if (DTD != null &&
  881. NodeType == XmlNodeType.Attribute &&
  882. sourceTextReader != null &&
  883. sourceTextReader.Normalization) {
  884. DTDAttributeDefinition def =
  885. dtd.AttListDecls [currentElement].Get (attrName);
  886. valueBuilder.Append (rawValue);
  887. valueBuilder.Replace ('\r', ' ');
  888. valueBuilder.Replace ('\n', ' ');
  889. valueBuilder.Replace ('\t', ' ');
  890. try {
  891. if (def.Datatype.TokenizedType != XmlTokenizedType.CDATA) {
  892. for (int i=0; i < valueBuilder.Length; i++) {
  893. if (valueBuilder [i] == ' ') {
  894. while (++i < valueBuilder.Length && valueBuilder [i] == ' ')
  895. valueBuilder.Remove (i, 1);
  896. }
  897. }
  898. return valueBuilder.ToString ().Trim (whitespaceChars);
  899. }
  900. else
  901. return valueBuilder.ToString ();
  902. } finally {
  903. valueBuilder.Length = 0;
  904. }
  905. }
  906. else
  907. return rawValue;
  908. }
  909. public override string Value {
  910. get {
  911. if (currentTextValue != null)
  912. return currentTextValue;
  913. // This check also covers value node of default attributes.
  914. if (IsDefault) {
  915. DTDAttributeDefinition def =
  916. dtd.AttListDecls [currentElement] [currentAttribute] as DTDAttributeDefinition;
  917. return sourceTextReader != null && sourceTextReader.Normalization ?
  918. def.NormalizedDefaultValue : def.DefaultValue;
  919. }
  920. // As to this property, MS.NET seems ignorant of EntityHandling...
  921. else if (NodeType == XmlNodeType.Attribute)// &&
  922. // currentEntityHandling == EntityHandling.ExpandEntities)
  923. return FilterNormalization (Name, attributeValues [currentAttribute]);
  924. else if (consumedAttribute)
  925. return FilterNormalization (Name, attributeValues [this.currentAttribute]);
  926. else
  927. return FilterNormalization (Name, reader.Value);
  928. }
  929. }
  930. public override string XmlLang {
  931. get {
  932. string val = this ["xml:lang"];
  933. return val != null ? val : reader.XmlLang;
  934. }
  935. }
  936. public XmlResolver XmlResolver {
  937. set {
  938. resolver = value;
  939. }
  940. }
  941. public override XmlSpace XmlSpace {
  942. get {
  943. string val = this ["xml:space"];
  944. switch (val) {
  945. case "preserve":
  946. return XmlSpace.Preserve;
  947. case "default":
  948. return XmlSpace.Default;
  949. default:
  950. return reader.XmlSpace;
  951. }
  952. }
  953. }
  954. }
  955. }