DTDValidatingReader.cs 36 KB

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