DTDValidatingReader.cs 35 KB

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