2
0

DTDValidatingReader.cs 35 KB

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