DTDValidatingReader.cs 37 KB

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