DTDValidatingReader.cs 32 KB

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