DTDValidatingReader.cs 36 KB

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