DTDValidatingReader.cs 33 KB

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