XmlTextReader.cs 77 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019
  1. //
  2. // System.Xml.XmlTextReader
  3. //
  4. // Author:
  5. // Jason Diamond ([email protected])
  6. // Adam Treat ([email protected])
  7. // Atsushi Enomoto ([email protected])
  8. //
  9. // (C) 2001, 2002 Jason Diamond http://injektilo.org/
  10. //
  11. // FIXME:
  12. //
  13. // NameTables aren't being used completely yet.
  14. //
  15. // Some thought needs to be given to performance. There's too many
  16. // strings being allocated.
  17. //
  18. using System;
  19. using System.Collections;
  20. using System.Collections.Specialized;
  21. using System.IO;
  22. using System.Text;
  23. using System.Xml.Schema;
  24. using Mono.Xml;
  25. using Mono.Xml.Native;
  26. namespace System.Xml
  27. {
  28. public class XmlTextReader : XmlReader, IXmlLineInfo
  29. {
  30. #region Constructors
  31. protected XmlTextReader ()
  32. {
  33. }
  34. public XmlTextReader (Stream input)
  35. : this (new XmlStreamReader (input))
  36. {
  37. }
  38. public XmlTextReader (string url)
  39. : this(url, new NameTable ())
  40. {
  41. }
  42. public XmlTextReader (TextReader input)
  43. : this (input, new NameTable ())
  44. {
  45. }
  46. protected XmlTextReader (XmlNameTable nt)
  47. : this (String.Empty, null, XmlNodeType.None, null)
  48. {
  49. }
  50. public XmlTextReader (Stream input, XmlNameTable nt)
  51. : this(new XmlStreamReader (input), nt)
  52. {
  53. }
  54. public XmlTextReader (string url, Stream input)
  55. : this (url, new XmlStreamReader (input))
  56. {
  57. }
  58. public XmlTextReader (string url, TextReader input)
  59. : this (url, input, new NameTable ())
  60. {
  61. }
  62. public XmlTextReader (string url, XmlNameTable nt)
  63. : this (url, new XmlStreamReader (url, null, null), nt)
  64. {
  65. }
  66. public XmlTextReader (TextReader input, XmlNameTable nt)
  67. : this (String.Empty, input, nt)
  68. {
  69. }
  70. public XmlTextReader (Stream xmlFragment, XmlNodeType fragType, XmlParserContext context)
  71. : this (context != null ? context.BaseURI : String.Empty,
  72. new XmlStreamReader (xmlFragment),
  73. fragType,
  74. context)
  75. {
  76. }
  77. public XmlTextReader (string url, Stream input, XmlNameTable nt)
  78. : this (url, new XmlStreamReader (input), nt)
  79. {
  80. }
  81. public XmlTextReader (string url, TextReader input, XmlNameTable nt)
  82. : this (url, input, XmlNodeType.Document, null)
  83. {
  84. }
  85. [MonoTODO("TODO as same as private XmlTextReader(TextReader, XmlNodeType, XmlParserContext)")]
  86. public XmlTextReader (string xmlFragment, XmlNodeType fragType, XmlParserContext context)
  87. : this (context != null ? context.BaseURI : String.Empty,
  88. new StringReader (xmlFragment),
  89. fragType,
  90. context)
  91. {
  92. }
  93. // TODO still remains as described at head of this file,
  94. // but it might not be TODO of the constructors...
  95. XmlTextReader (string url, TextReader fragment, XmlNodeType fragType, XmlParserContext context)
  96. {
  97. InitializeContext (url, context, fragment, fragType);
  98. }
  99. #endregion
  100. #region Properties
  101. public override int AttributeCount
  102. {
  103. get { return attributes.Count; }
  104. }
  105. public override string BaseURI
  106. {
  107. get { return parserContext.BaseURI; }
  108. }
  109. public override int Depth
  110. {
  111. get {
  112. return elementDepth;
  113. }
  114. }
  115. public Encoding Encoding
  116. {
  117. get { return parserContext.Encoding; }
  118. }
  119. public override bool EOF
  120. {
  121. get
  122. {
  123. return
  124. readState == ReadState.EndOfFile ||
  125. readState == ReadState.Closed;
  126. }
  127. }
  128. public override bool HasValue
  129. {
  130. get {
  131. if (this.valueBuilderAvailable)
  132. return valueBuilder.Length != 0;
  133. else
  134. return value != String.Empty;
  135. }
  136. }
  137. public override bool IsDefault
  138. {
  139. get
  140. {
  141. // XmlTextReader does not expand default attributes.
  142. return false;
  143. }
  144. }
  145. public override bool IsEmptyElement
  146. {
  147. get { return isEmptyElement; }
  148. }
  149. public override string this [int i]
  150. {
  151. get { return GetAttribute (i); }
  152. }
  153. public override string this [string name]
  154. {
  155. get { return GetAttribute (name); }
  156. }
  157. public override string this [string localName, string namespaceName]
  158. {
  159. get { return GetAttribute (localName, namespaceName); }
  160. }
  161. public int LineNumber
  162. {
  163. get { return currentInput.LineNumber; }
  164. }
  165. public int LinePosition
  166. {
  167. get { return currentInput.LinePosition; }
  168. }
  169. public override string LocalName
  170. {
  171. get { return localName; }
  172. }
  173. public override string Name
  174. {
  175. get { return name; }
  176. }
  177. public bool Namespaces
  178. {
  179. get { return namespaces; }
  180. set {
  181. if (readState != ReadState.Initial)
  182. throw new InvalidOperationException ("Namespaces have to be set before reading.");
  183. namespaces = value;
  184. }
  185. }
  186. public override string NamespaceURI
  187. {
  188. get { return namespaceURI; }
  189. }
  190. public override XmlNameTable NameTable
  191. {
  192. get { return parserContext.NameTable; }
  193. }
  194. public override XmlNodeType NodeType
  195. {
  196. get { return nodeType; }
  197. }
  198. [MonoTODO]
  199. public bool Normalization
  200. {
  201. get { return normalization; }
  202. set { normalization = value; }
  203. }
  204. public override string Prefix
  205. {
  206. get { return prefix; }
  207. }
  208. public override char QuoteChar
  209. {
  210. get {
  211. // value string holds attribute quotation char.
  212. if (NodeType == XmlNodeType.Attribute)
  213. return value [0];
  214. else
  215. return '"';
  216. }
  217. }
  218. public override ReadState ReadState
  219. {
  220. get { return readState; }
  221. }
  222. public override string Value
  223. {
  224. get {
  225. string v = value;
  226. if (valueBuilderAvailable)
  227. v = valueBuilder.ToString ();
  228. if(NodeType == XmlNodeType.Attribute)
  229. return UnescapeAttributeValue(v);
  230. else
  231. return v;
  232. }
  233. }
  234. public WhitespaceHandling WhitespaceHandling
  235. {
  236. get { return whitespaceHandling; }
  237. set { whitespaceHandling = value; }
  238. }
  239. public override string XmlLang
  240. {
  241. get { return parserContext.XmlLang; }
  242. }
  243. public XmlResolver XmlResolver
  244. {
  245. set { resolver = value; }
  246. }
  247. public override XmlSpace XmlSpace
  248. {
  249. get { return parserContext.XmlSpace; }
  250. }
  251. #endregion
  252. #region Methods
  253. public override void Close ()
  254. {
  255. readState = ReadState.Closed;
  256. foreach (XmlParserInput input in parserInputStack.ToArray ())
  257. input.Close ();
  258. this.currentInput.Close ();
  259. }
  260. public override string GetAttribute (int i)
  261. {
  262. if (i > attributes.Count)
  263. throw new ArgumentOutOfRangeException ("i is smaller than AttributeCount");
  264. else
  265. return UnescapeAttributeValue (attributes [orderedAttributes [i]] as string);
  266. }
  267. // MS.NET 1.0 documentation says that this method returns String.Empty for
  268. // not-exist attribute, but in fact it returns null.
  269. // That description is corrected in MS.NET 1.1 documentation.
  270. public override string GetAttribute (string name)
  271. {
  272. return UnescapeAttributeValue (attributes [name] as string);
  273. }
  274. private int GetIndexOfQualifiedAttribute (string localName, string namespaceURI)
  275. {
  276. for(int i = 0; i < orderedAttributes.Count; i++)
  277. {
  278. string thisName = (string) orderedAttributes [i];
  279. int indexOfColon = thisName.IndexOf (':');
  280. if (indexOfColon != -1) {
  281. string thisLocalName = thisName.Substring (indexOfColon + 1);
  282. if (localName == thisLocalName) {
  283. string thisPrefix = thisName.Substring (0, indexOfColon);
  284. string thisNamespaceURI = LookupNamespace (thisPrefix);
  285. if (namespaceURI == thisNamespaceURI)
  286. return i;
  287. }
  288. } else if (localName == "xmlns" && namespaceURI == "http://www.w3.org/2000/xmlns/" && thisName == "xmlns")
  289. return i;
  290. }
  291. return -1;
  292. }
  293. internal XmlParserContext GetInternalParserContext ()
  294. {
  295. return parserContext;
  296. }
  297. public override string GetAttribute (string localName, string namespaceURI)
  298. {
  299. int idx = this.GetIndexOfQualifiedAttribute (localName, namespaceURI);
  300. if (idx < 0)
  301. return null;
  302. return UnescapeAttributeValue (attributes [orderedAttributes [idx]] as string);
  303. }
  304. [MonoTODO]
  305. public TextReader GetRemainder ()
  306. {
  307. throw new NotImplementedException ();
  308. }
  309. bool IXmlLineInfo.HasLineInfo ()
  310. {
  311. return true;
  312. }
  313. public override string LookupNamespace (string prefix)
  314. {
  315. return parserContext.NamespaceManager.LookupNamespace (prefix);
  316. }
  317. public override void MoveToAttribute (int i)
  318. {
  319. MoveToElement ();
  320. if (attributes == null || orderedAttributes.Count < i || i < 0)
  321. throw new ArgumentOutOfRangeException ("attribute index out of range.");
  322. if (orderedAttributesEnumerator == null) {
  323. SaveProperties ();
  324. }
  325. orderedAttributesEnumerator = orderedAttributes.GetEnumerator ();
  326. for (int n=0; n<=i; n++)
  327. orderedAttributesEnumerator.MoveNext();
  328. string name = orderedAttributes [i] as string;
  329. string value = attributes [name] as string;
  330. SetProperties (
  331. XmlNodeType.Attribute, // nodeType
  332. name, // name
  333. false, // isEmptyElement
  334. value, // value
  335. false // clearAttributes
  336. );
  337. attributeValuePos = 0;
  338. }
  339. public override bool MoveToAttribute (string name)
  340. {
  341. MoveToElement ();
  342. bool match = false;
  343. if (attributes == null)
  344. return false;
  345. if (orderedAttributesEnumerator == null) {
  346. SaveProperties ();
  347. }
  348. orderedAttributesEnumerator = orderedAttributes.GetEnumerator ();
  349. while (orderedAttributesEnumerator.MoveNext ()) {
  350. if(name == orderedAttributesEnumerator.Current as string) {
  351. match = true;
  352. break;
  353. }
  354. }
  355. if (match) {
  356. string value = attributes [name] as string;
  357. SetProperties (
  358. XmlNodeType.Attribute, // nodeType
  359. name, // name
  360. false, // isEmptyElement
  361. value, // value
  362. false // clearAttributes
  363. );
  364. attributeValuePos = 0;
  365. }
  366. return match;
  367. }
  368. public override bool MoveToAttribute (string localName, string namespaceName)
  369. {
  370. MoveToElement ();
  371. if (attributes == null)
  372. return false;
  373. int idx = GetIndexOfQualifiedAttribute (localName, namespaceName);
  374. if (idx < 0)
  375. return false;
  376. MoveToAttribute (idx);
  377. return true;
  378. }
  379. public override bool MoveToElement ()
  380. {
  381. if (orderedAttributesEnumerator != null) {
  382. orderedAttributesEnumerator = null;
  383. if (isPropertySaved)
  384. RestoreProperties ();
  385. return true;
  386. }
  387. return false;
  388. }
  389. public override bool MoveToFirstAttribute ()
  390. {
  391. MoveToElement ();
  392. return MoveToNextAttribute ();
  393. }
  394. public override bool MoveToNextAttribute ()
  395. {
  396. if (attributes == null)
  397. return false;
  398. if (orderedAttributesEnumerator == null) {
  399. SaveProperties ();
  400. orderedAttributesEnumerator = orderedAttributes.GetEnumerator ();
  401. }
  402. if (orderedAttributesEnumerator.MoveNext ()) {
  403. string name = orderedAttributesEnumerator.Current as string;
  404. string value = attributes [name] as string;
  405. SetProperties (
  406. XmlNodeType.Attribute, // nodeType
  407. name, // name
  408. false, // isEmptyElement
  409. value, // value
  410. false // clearAttributes
  411. );
  412. attributeValuePos = 0;
  413. return true;
  414. }
  415. return false;
  416. }
  417. public override bool Read ()
  418. {
  419. bool more = false;
  420. isPropertySaved = false;
  421. readState = ReadState.Interactive;
  422. // It was moved from end of ReadStartTag ().
  423. if (depthUp)
  424. ++depth;
  425. depthUp = false;
  426. more = ReadContent ();
  427. if (depth == 0 && !allowMultipleRoot && (IsEmptyElement || NodeType == XmlNodeType.EndElement))
  428. currentState = XmlNodeType.EndElement;
  429. if (maybeTextDecl != 0)
  430. maybeTextDecl--;
  431. if (!more && startNodeType == XmlNodeType.Document && currentState != XmlNodeType.EndElement)
  432. throw new XmlException ("Document element was not appeared.");
  433. return more;
  434. }
  435. public override bool ReadAttributeValue ()
  436. {
  437. // 'attributeString' holds real string value (without their
  438. // quotation characters).
  439. //
  440. // 'attributeValuePos' holds current position
  441. // of 'attributeString' while iterating ReadAttribute().
  442. // It may be:
  443. // -1 if ReadAttributeValue() has already finished.
  444. // 0 if ReadAttributeValue() ready to start reading.
  445. // >0 if ReadAttributeValue() already got 1 or more values
  446. //
  447. // local 'refPosition' holds the position on the
  448. // attributeString which may be used next time.
  449. if (attributeValuePos < 0)
  450. return false;
  451. // If not started, then initialize attributeString when parsing is at start.
  452. if (attributeValuePos == 0)
  453. attributeString =
  454. value.Substring (1, value.Length - 2);
  455. // It occurs when attribute dully consists of entity reference.
  456. if (attributeValuePos == attributeString.Length)
  457. return false;
  458. returnEntityReference = false;
  459. value = String.Empty;
  460. int refPosition;
  461. int loop = 0;
  462. do {
  463. refPosition = attributeString.IndexOf ('&', attributeValuePos);
  464. if (refPosition < 0) {
  465. // Reached to the end of value string.
  466. value += attributeString.Substring (attributeValuePos);
  467. attributeValuePos = -1;
  468. break;
  469. } else if (refPosition == attributeValuePos) {
  470. string parsed = ReadAttributeValueReference ();
  471. if (parsed != null)
  472. value += parsed;
  473. else {
  474. // Found that an entity reference starts from this point.
  475. // reset position to after '&'.
  476. attributeValuePos = refPosition;
  477. if (value.Length <= 0) {
  478. int endNamePos = attributeString.IndexOf (";", attributeValuePos);
  479. value = attributeString.Substring (attributeValuePos+1, endNamePos - attributeValuePos - 1);
  480. attributeValuePos += value.Length + 2;
  481. returnEntityReference = true;
  482. }
  483. break;
  484. }
  485. } else {
  486. value += attributeString.Substring (attributeValuePos,
  487. refPosition - attributeValuePos);
  488. attributeValuePos = refPosition;
  489. continue;
  490. }
  491. } while (++loop > 0);
  492. if (returnEntityReference)
  493. SetProperties (XmlNodeType.EntityReference,
  494. value,
  495. false,
  496. String.Empty,
  497. false);
  498. else
  499. SetProperties (XmlNodeType.Text,
  500. "",
  501. false,
  502. value,
  503. false);
  504. returnEntityReference = false;
  505. return true;
  506. }
  507. [MonoTODO]
  508. public int ReadBase64 (byte [] buffer, int offset, int length)
  509. {
  510. throw new NotImplementedException ();
  511. }
  512. [MonoTODO]
  513. public int ReadBinHex (byte [] buffer, int offset, int length)
  514. {
  515. throw new NotImplementedException ();
  516. }
  517. [MonoTODO]
  518. public int ReadChars (char [] buffer, int offset, int length)
  519. {
  520. throw new NotImplementedException ();
  521. }
  522. #if NET_1_0
  523. public override string ReadInnerXml ()
  524. {
  525. if (readState != ReadState.Interactive)
  526. return String.Empty;
  527. switch (NodeType) {
  528. case XmlNodeType.Attribute:
  529. return value.Substring (1, value.Length - 2);
  530. case XmlNodeType.Element:
  531. if (IsEmptyElement)
  532. return String.Empty;
  533. int startDepth = depth;
  534. if (innerXmlBuilder == null)
  535. innerXmlBuilder = new StringBuilder ();
  536. innerXmlBuilder.Length = 0;
  537. bool loop = true;
  538. do {
  539. Read ();
  540. if (NodeType ==XmlNodeType.None)
  541. throw new XmlException ("unexpected end of xml.");
  542. else if (NodeType == XmlNodeType.EndElement && depth == startDepth) {
  543. loop = false;
  544. Read ();
  545. }
  546. else
  547. innerXmlBuilder.Append (currentTag);
  548. } while (loop);
  549. string xml = innerXmlBuilder.ToString ();
  550. innerXmlBuilder.Length = 0;
  551. return xml;
  552. case XmlNodeType.None:
  553. // MS document is incorrect. Seems not to progress.
  554. return String.Empty;
  555. default:
  556. Read ();
  557. return String.Empty;
  558. }
  559. }
  560. public override string ReadOuterXml ()
  561. {
  562. if (readState != ReadState.Interactive)
  563. return String.Empty;
  564. switch (NodeType) {
  565. case XmlNodeType.Attribute:
  566. // strictly incompatible with MS... (it holds spaces attribute between name, value and "=" char (very trivial).
  567. return String.Format ("{0}={1}{2}{1}", Name, QuoteChar, ReadInnerXml ());
  568. case XmlNodeType.Element:
  569. bool isEmpty = IsEmptyElement;
  570. string startTag = currentTag.ToString ();
  571. string name = Name;
  572. if (NodeType == XmlNodeType.Element && !isEmpty)
  573. return String.Format ("{0}{1}</{2}>", startTag, ReadInnerXml (), name);
  574. else
  575. return currentTag.ToString ();
  576. case XmlNodeType.None:
  577. // MS document is incorrect. Seems not to progress.
  578. return String.Empty;
  579. default:
  580. Read ();
  581. return String.Empty;
  582. }
  583. }
  584. #endif
  585. public override string ReadString ()
  586. {
  587. return ReadStringInternal ();
  588. }
  589. public void ResetState ()
  590. {
  591. Init ();
  592. }
  593. public override void ResolveEntity ()
  594. {
  595. // XmlTextReader does not resolve entities.
  596. throw new InvalidOperationException ("XmlTextReader cannot resolve external entities.");
  597. }
  598. #endregion
  599. #region Internals
  600. // Parsed DTD Objects
  601. internal DTDObjectModel DTD {
  602. get { return parserContext.Dtd; }
  603. }
  604. internal bool MaybeTextDecl {
  605. set { if (value) this.maybeTextDecl = 2; }
  606. }
  607. #endregion
  608. #region Privates
  609. private XmlParserContext parserContext;
  610. private XmlParserInput currentInput;
  611. private Stack parserInputStack;
  612. private ReadState readState;
  613. private int depth;
  614. private int elementDepth;
  615. private bool depthUp;
  616. private bool popScope;
  617. private Stack elementStack;
  618. private bool allowMultipleRoot;
  619. private bool isStandalone;
  620. private XmlNodeType nodeType;
  621. private string name;
  622. private string prefix;
  623. private string localName;
  624. private string namespaceURI;
  625. private bool isEmptyElement;
  626. private string value;
  627. private StringBuilder valueBuilder;
  628. private bool valueBuilderAvailable = false;
  629. private bool isPropertySaved;
  630. private XmlNodeType saveNodeType;
  631. private string saveName;
  632. private string savePrefix;
  633. private string saveLocalName;
  634. private string saveNamespaceURI;
  635. private bool saveIsEmptyElement;
  636. private Hashtable attributes;
  637. private ArrayList orderedAttributes;
  638. private IEnumerator orderedAttributesEnumerator;
  639. private bool returnEntityReference;
  640. private string entityReferenceName;
  641. private char [] nameBuffer;
  642. private int nameLength;
  643. private int nameCapacity;
  644. private const int initialNameCapacity = 256;
  645. private StringBuilder valueBuffer;
  646. // A buffer for ReadContent for ReadOuterXml
  647. private StringBuilder currentTag {
  648. get {
  649. return currentInput.CurrentMarkup;
  650. }
  651. }
  652. private string attributeString;
  653. private int attributeValuePos;
  654. // This should be only referenced(used) by ReadInnerXml(). Kind of flyweight pattern.
  655. private StringBuilder innerXmlBuilder;
  656. // Parameter entity placeholder
  657. private Hashtable parameterEntities;
  658. private int dtdIncludeSect;
  659. private XmlNodeType startNodeType;
  660. // State machine attribute.
  661. // XmlDeclaration: after the first node.
  662. // DocumentType: after doctypedecl
  663. // Element: inside document element
  664. // EndElement: after document element
  665. private XmlNodeType currentState;
  666. private int maybeTextDecl;
  667. // These values are never re-initialized.
  668. private XmlResolver resolver = new XmlUrlResolver ();
  669. private bool namespaces = true;
  670. private WhitespaceHandling whitespaceHandling = WhitespaceHandling.All;
  671. private bool normalization = false;
  672. private void Init ()
  673. {
  674. readState = ReadState.Initial;
  675. currentState = XmlNodeType.None;
  676. maybeTextDecl = 0;
  677. allowMultipleRoot = false;
  678. depth = 0;
  679. depthUp = false;
  680. popScope = false;
  681. parserInputStack = new Stack ();
  682. elementStack = new Stack();
  683. nodeType = XmlNodeType.None;
  684. name = String.Empty;
  685. prefix = String.Empty;
  686. localName = string.Empty;
  687. isEmptyElement = false;
  688. value = String.Empty;
  689. attributes = new Hashtable ();
  690. attributeString = String.Empty;
  691. orderedAttributes = new ArrayList ();
  692. orderedAttributesEnumerator = null;
  693. returnEntityReference = false;
  694. entityReferenceName = String.Empty;
  695. nameBuffer = new char [initialNameCapacity];
  696. nameLength = 0;
  697. nameCapacity = initialNameCapacity;
  698. valueBuffer = new StringBuilder (8192);
  699. parameterEntities = new Hashtable ();
  700. }
  701. private void InitializeContext (string url, XmlParserContext context, TextReader fragment, XmlNodeType fragType)
  702. {
  703. startNodeType = fragType;
  704. parserContext = context;
  705. if (context == null) {
  706. XmlNameTable nt = new NameTable ();
  707. parserContext = new XmlParserContext (nt,
  708. new XmlNamespaceManager (nt),
  709. String.Empty,
  710. XmlSpace.None);
  711. }
  712. if (url != null && url != String.Empty) {
  713. string path = Path.GetFullPath ("./a");
  714. Uri uri = new Uri (new Uri (path), url);
  715. parserContext.BaseURI = uri.ToString ();
  716. }
  717. Init ();
  718. switch (fragType) {
  719. case XmlNodeType.Attribute:
  720. value = String.Format ("{0}{1}{0}", "'", fragment.ReadToEnd ().Replace ("'", "&apos;"));
  721. break;
  722. case XmlNodeType.Element:
  723. currentState = XmlNodeType.Element;
  724. allowMultipleRoot = true;
  725. break;
  726. case XmlNodeType.Document:
  727. break;
  728. default:
  729. throw new XmlException (String.Format ("NodeType {0} is not allowed to create XmlTextReader.", fragType));
  730. }
  731. this.currentInput = new XmlParserInput (fragment, url);
  732. StreamReader sr = fragment as StreamReader;
  733. }
  734. // Use this method rather than setting the properties
  735. // directly so that all the necessary properties can
  736. // be changed in harmony with each other. Maybe the
  737. // fields should be in a seperate class to help enforce
  738. // this.
  739. private void SetProperties (
  740. XmlNodeType nodeType,
  741. string name,
  742. bool isEmptyElement,
  743. string value,
  744. bool clearAttributes)
  745. {
  746. this.nodeType = nodeType;
  747. this.name = name;
  748. this.isEmptyElement = isEmptyElement;
  749. this.value = value;
  750. this.elementDepth = depth;
  751. this.valueBuilderAvailable = false;
  752. if (clearAttributes)
  753. ClearAttributes ();
  754. if (namespaces) {
  755. int indexOfColon = name.IndexOf (':');
  756. if (indexOfColon == -1) {
  757. prefix = String.Empty;
  758. localName = name;
  759. } else {
  760. prefix = name.Substring (0, indexOfColon);
  761. localName = name.Substring (indexOfColon + 1);
  762. }
  763. } else {
  764. prefix = String.Empty;
  765. localName = name;
  766. }
  767. switch (nodeType) {
  768. case XmlNodeType.Attribute:
  769. if (prefix == string.Empty) namespaceURI = string.Empty;
  770. else namespaceURI = LookupNamespace (prefix);
  771. if (localName == "xmlns" && prefix == "")
  772. namespaceURI = "http://www.w3.org/2000/xmlns/";
  773. break;
  774. case XmlNodeType.Element:
  775. case XmlNodeType.EndElement:
  776. namespaceURI = LookupNamespace (prefix);
  777. break;
  778. default:
  779. namespaceURI = "";
  780. break;
  781. }
  782. }
  783. private void SetProperties (
  784. XmlNodeType nodeType,
  785. string name,
  786. bool isEmptyElement,
  787. StringBuilder value,
  788. bool clearAttributes) {
  789. SetProperties (nodeType, name, isEmptyElement, (string)null, clearAttributes);
  790. this.valueBuilderAvailable = true;
  791. this.valueBuilder = value;
  792. }
  793. private void SaveProperties ()
  794. {
  795. // If already saved, then return.
  796. if (isPropertySaved)
  797. return;
  798. saveNodeType = nodeType;
  799. saveName = name;
  800. savePrefix = prefix;
  801. saveLocalName = localName;
  802. saveNamespaceURI = namespaceURI;
  803. saveIsEmptyElement = isEmptyElement;
  804. // An element's value is always String.Empty.
  805. isPropertySaved = true;
  806. }
  807. private void RestoreProperties ()
  808. {
  809. nodeType = saveNodeType;
  810. name = saveName;
  811. prefix = savePrefix;
  812. localName = saveLocalName;
  813. namespaceURI = saveNamespaceURI;
  814. isEmptyElement = saveIsEmptyElement;
  815. value = String.Empty;
  816. isPropertySaved = false;
  817. }
  818. private void AddAttribute (string name, string value)
  819. {
  820. if (attributes.ContainsKey (name))
  821. throw new XmlException (this as IXmlLineInfo,
  822. String.Format ("Attribute {0} already exists.", name));
  823. attributes.Add (name, value);
  824. orderedAttributes.Add (name);
  825. }
  826. private void ClearAttributes ()
  827. {
  828. if (attributes.Count > 0) {
  829. attributes.Clear ();
  830. orderedAttributes.Clear ();
  831. }
  832. orderedAttributesEnumerator = null;
  833. }
  834. private int PeekChar ()
  835. {
  836. return currentInput.PeekChar ();
  837. }
  838. private int ReadChar ()
  839. {
  840. return currentInput.ReadChar ();
  841. }
  842. // This should really keep track of some state so
  843. // that it's not possible to have more than one document
  844. // element or text outside of the document element.
  845. private bool ReadContent ()
  846. {
  847. currentTag.Length = 0;
  848. if (popScope) {
  849. parserContext.NamespaceManager.PopScope ();
  850. popScope = false;
  851. }
  852. if (returnEntityReference)
  853. SetEntityReferenceProperties ();
  854. else {
  855. switch (PeekChar ()) {
  856. case '<':
  857. ReadChar ();
  858. ReadTag ();
  859. break;
  860. case '\r': goto case ' ';
  861. case '\n': goto case ' ';
  862. case '\t': goto case ' ';
  863. case ' ':
  864. if (whitespaceHandling == WhitespaceHandling.All ||
  865. whitespaceHandling == WhitespaceHandling.Significant)
  866. ReadWhitespace ();
  867. else {
  868. SkipWhitespace ();
  869. return ReadContent ();
  870. }
  871. break;
  872. case -1:
  873. if (depth > 0)
  874. throw new XmlException ("unexpected end of file. Current depth is " + depth);
  875. readState = ReadState.EndOfFile;
  876. SetProperties (
  877. XmlNodeType.None, // nodeType
  878. String.Empty, // name
  879. false, // isEmptyElement
  880. String.Empty, // value
  881. true // clearAttributes
  882. );
  883. break;
  884. default:
  885. ReadText (true);
  886. break;
  887. }
  888. }
  889. if (NodeType == XmlNodeType.XmlDeclaration && maybeTextDecl == 1)
  890. return ReadContent ();
  891. return this.ReadState != ReadState.EndOfFile;
  892. }
  893. private void SetEntityReferenceProperties ()
  894. {
  895. /*
  896. if (resolver != null) {
  897. if (DTD == null)
  898. throw new XmlException (this as IXmlLineInfo,
  899. "Entity reference is not allowed without document type declaration.");
  900. else if((!DTD.InternalSubsetHasPEReference || isStandalone) &&
  901. DTD.EntityDecls [entityReferenceName] == null)
  902. throw new XmlException (this as IXmlLineInfo,
  903. "Required entity declaration for '" + entityReferenceName + "' was not found.");
  904. string dummy = DTD.EntityDecls [entityReferenceName].EntityValue;
  905. }
  906. */
  907. SetProperties (
  908. XmlNodeType.EntityReference, // nodeType
  909. entityReferenceName, // name
  910. false, // isEmptyElement
  911. String.Empty, // value
  912. true // clearAttributes
  913. );
  914. returnEntityReference = false;
  915. entityReferenceName = String.Empty;
  916. }
  917. // The leading '<' has already been consumed.
  918. private void ReadTag ()
  919. {
  920. switch (PeekChar ())
  921. {
  922. case '/':
  923. ReadChar ();
  924. ReadEndTag ();
  925. break;
  926. case '?':
  927. ReadChar ();
  928. ReadProcessingInstruction ();
  929. break;
  930. case '!':
  931. ReadChar ();
  932. ReadDeclaration ();
  933. break;
  934. default:
  935. ReadStartTag ();
  936. break;
  937. }
  938. }
  939. // The leading '<' has already been consumed.
  940. private void ReadStartTag ()
  941. {
  942. if (currentState == XmlNodeType.EndElement)
  943. throw new XmlException (this as IXmlLineInfo,
  944. "Element cannot appear in this state.");
  945. currentState = XmlNodeType.Element;
  946. parserContext.NamespaceManager.PushScope ();
  947. string name = ReadName ();
  948. if (currentState == XmlNodeType.EndElement)
  949. throw new XmlException (this as IXmlLineInfo,"document has terminated, cannot open new element");
  950. bool isEmptyElement = false;
  951. ClearAttributes ();
  952. SkipWhitespace ();
  953. if (XmlChar.IsFirstNameChar (PeekChar ()))
  954. ReadAttributes (false);
  955. string baseUri = GetAttribute ("xml:base");
  956. if (baseUri != null)
  957. parserContext.BaseURI = baseUri;
  958. string xmlLang = GetAttribute ("xml:lang");
  959. if (xmlLang != null)
  960. parserContext.XmlLang = xmlLang;
  961. string xmlSpaceAttr = GetAttribute ("xml:space");
  962. if (xmlSpaceAttr != null) {
  963. if (xmlSpaceAttr == "preserve")
  964. parserContext.XmlSpace = XmlSpace.Preserve;
  965. else if (xmlSpaceAttr == "default")
  966. parserContext.XmlSpace = XmlSpace.Default;
  967. else
  968. throw new XmlException (this as IXmlLineInfo,String.Format ("Invalid xml:space value: {0}", xmlSpaceAttr));
  969. }
  970. if (PeekChar () == '/') {
  971. ReadChar ();
  972. isEmptyElement = true;
  973. popScope = true;
  974. }
  975. else {
  976. depthUp = true;
  977. elementStack.Push (name);
  978. parserContext.PushScope ();
  979. }
  980. Expect ('>');
  981. SetProperties (
  982. XmlNodeType.Element, // nodeType
  983. name, // name
  984. isEmptyElement, // isEmptyElement
  985. String.Empty, // value
  986. false // clearAttributes
  987. );
  988. }
  989. // The reader is positioned on the first character
  990. // of the element's name.
  991. private void ReadEndTag ()
  992. {
  993. if (currentState != XmlNodeType.Element)
  994. throw new XmlException (this as IXmlLineInfo,
  995. "End tag cannot appear in this state.");
  996. string name = ReadName ();
  997. if (elementStack.Count == 0)
  998. throw new XmlException (this as IXmlLineInfo,"closing element without matching opening element");
  999. string expected = (string)elementStack.Pop();
  1000. if (expected != name)
  1001. throw new XmlException (this as IXmlLineInfo,String.Format ("unmatched closing element: expected {0} but found {1}", expected, name));
  1002. parserContext.PopScope ();
  1003. SkipWhitespace ();
  1004. Expect ('>');
  1005. --depth;
  1006. SetProperties (
  1007. XmlNodeType.EndElement, // nodeType
  1008. name, // name
  1009. false, // isEmptyElement
  1010. String.Empty, // value
  1011. true // clearAttributes
  1012. );
  1013. popScope = true;
  1014. }
  1015. private void AppendNameChar (int ch)
  1016. {
  1017. CheckNameCapacity ();
  1018. nameBuffer [nameLength++] = (char)ch;
  1019. }
  1020. private void CheckNameCapacity ()
  1021. {
  1022. if (nameLength == nameCapacity) {
  1023. nameCapacity = nameCapacity * 2;
  1024. char [] oldNameBuffer = nameBuffer;
  1025. nameBuffer = new char [nameCapacity];
  1026. Array.Copy (oldNameBuffer, nameBuffer, nameLength);
  1027. }
  1028. }
  1029. private string CreateNameString ()
  1030. {
  1031. return parserContext.NameTable.Add (nameBuffer, 0, nameLength);
  1032. }
  1033. private void AppendValueChar (int ch)
  1034. {
  1035. valueBuffer.Append ((char)ch);
  1036. }
  1037. private string CreateValueString ()
  1038. {
  1039. return valueBuffer.ToString ();
  1040. }
  1041. private void ClearValueBuffer ()
  1042. {
  1043. valueBuffer.Length = 0;
  1044. }
  1045. // The reader is positioned on the first character
  1046. // of the text.
  1047. private void ReadText (bool notWhitespace)
  1048. {
  1049. if (currentState != XmlNodeType.Element)
  1050. throw new XmlException (this as IXmlLineInfo,
  1051. "Text node cannot appear in this state.");
  1052. if (notWhitespace)
  1053. ClearValueBuffer ();
  1054. int ch = PeekChar ();
  1055. int previousCloseBracketLine = 0;
  1056. int previousCloseBracketColumn = 0;
  1057. while (ch != '<' && ch != -1) {
  1058. if (ch == '&') {
  1059. ReadChar ();
  1060. if (ReadReference (false))
  1061. break;
  1062. } else {
  1063. if (XmlConstructs.IsInvalid (ch))
  1064. throw new XmlException (this as IXmlLineInfo,
  1065. "Not allowed character was found.");
  1066. AppendValueChar (ReadChar ());
  1067. if (ch == ']') {
  1068. if (previousCloseBracketColumn == LinePosition - 1 &&
  1069. previousCloseBracketLine == LineNumber)
  1070. if (PeekChar () == '>')
  1071. throw new XmlException (this as IXmlLineInfo,
  1072. "Inside text content, character sequence ']]>' is not allowed.");
  1073. previousCloseBracketColumn = LinePosition;
  1074. previousCloseBracketLine = LineNumber;
  1075. }
  1076. }
  1077. ch = PeekChar ();
  1078. notWhitespace = true;
  1079. }
  1080. if (returnEntityReference && valueBuffer.Length == 0) {
  1081. SetEntityReferenceProperties ();
  1082. } else {
  1083. XmlNodeType nodeType = notWhitespace ?
  1084. XmlNodeType.Text : XmlNodeType.Whitespace;
  1085. SetProperties (
  1086. nodeType, // nodeType
  1087. String.Empty, // name
  1088. false, // isEmptyElement
  1089. valueBuffer, // value
  1090. true // clearAttributes
  1091. );
  1092. }
  1093. }
  1094. // The leading '&' has already been consumed.
  1095. // Returns true if the entity reference isn't a simple
  1096. // character reference or one of the predefined entities.
  1097. // This allows the ReadText method to break so that the
  1098. // next call to Read will return the EntityReference node.
  1099. private bool ReadReference (bool ignoreEntityReferences)
  1100. {
  1101. if (PeekChar () == '#') {
  1102. ReadChar ();
  1103. ReadCharacterReference ();
  1104. } else
  1105. ReadEntityReference (ignoreEntityReferences);
  1106. return returnEntityReference;
  1107. }
  1108. private void ReadCharacterReference ()
  1109. {
  1110. int value = 0;
  1111. if (PeekChar () == 'x') {
  1112. ReadChar ();
  1113. while (PeekChar () != ';' && PeekChar () != -1) {
  1114. int ch = ReadChar ();
  1115. if (ch >= '0' && ch <= '9')
  1116. value = (value << 4) + ch - '0';
  1117. else if (ch >= 'A' && ch <= 'F')
  1118. value = (value << 4) + ch - 'A' + 10;
  1119. else if (ch >= 'a' && ch <= 'f')
  1120. value = (value << 4) + ch - 'a' + 10;
  1121. else
  1122. throw new XmlException (this as IXmlLineInfo,
  1123. String.Format (
  1124. "invalid hexadecimal digit: {0} (#x{1:X})",
  1125. (char)ch,
  1126. ch));
  1127. }
  1128. } else {
  1129. while (PeekChar () != ';' && PeekChar () != -1) {
  1130. int ch = ReadChar ();
  1131. if (ch >= '0' && ch <= '9')
  1132. value = value * 10 + ch - '0';
  1133. else
  1134. throw new XmlException (this as IXmlLineInfo,
  1135. String.Format (
  1136. "invalid decimal digit: {0} (#x{1:X})",
  1137. (char)ch,
  1138. ch));
  1139. }
  1140. }
  1141. ReadChar (); // ';'
  1142. // FIXME: how to handle such chars larger than 0xffff?
  1143. if (value < 0xffff && !XmlConstructs.IsValid (value))
  1144. throw new XmlException (this as IXmlLineInfo,
  1145. "Referenced character was not allowed in XML.");
  1146. AppendValueChar (value);
  1147. }
  1148. private void ReadEntityReference (bool ignoreEntityReferences)
  1149. {
  1150. nameLength = 0;
  1151. int ch = PeekChar ();
  1152. while (ch != ';' && ch != -1) {
  1153. AppendNameChar (ReadChar ());
  1154. ch = PeekChar ();
  1155. }
  1156. Expect (';');
  1157. string name = CreateNameString ();
  1158. if (!XmlChar.IsName (name))
  1159. throw new XmlException (this as IXmlLineInfo,
  1160. "Invalid entity reference name was found.");
  1161. char predefined = XmlChar.GetPredefinedEntity (name);
  1162. if (predefined != 0)
  1163. AppendValueChar (predefined);
  1164. else {
  1165. if (ignoreEntityReferences) {
  1166. AppendValueChar ('&');
  1167. foreach (char ch2 in name) {
  1168. AppendValueChar (ch2);
  1169. }
  1170. AppendValueChar (';');
  1171. } else {
  1172. returnEntityReference = true;
  1173. entityReferenceName = name;
  1174. }
  1175. }
  1176. }
  1177. // The reader is positioned on the first character of
  1178. // the attribute name.
  1179. private void ReadAttributes (bool allowPIEnd)
  1180. {
  1181. int peekChar = -1;
  1182. bool requireWhitespace = false;
  1183. do {
  1184. if (!SkipWhitespace () && requireWhitespace)
  1185. throw new XmlException ("Unexpected token. Name is required here.");
  1186. string name = ReadName ();
  1187. SkipWhitespace ();
  1188. Expect ('=');
  1189. SkipWhitespace ();
  1190. string value = ReadAttribute (false);
  1191. if (name == "xmlns")
  1192. parserContext.NamespaceManager.AddNamespace (String.Empty, UnescapeAttributeValue (value));
  1193. else if (name.StartsWith ("xmlns:"))
  1194. parserContext.NamespaceManager.AddNamespace (name.Substring (6), UnescapeAttributeValue (value));
  1195. AddAttribute (name, value);
  1196. if (!SkipWhitespace ())
  1197. requireWhitespace = true;
  1198. peekChar = PeekChar ();
  1199. if (peekChar == '?' && allowPIEnd)
  1200. break;
  1201. } while (peekChar != '/' && peekChar != '>' && peekChar != -1);
  1202. }
  1203. // The reader is positioned on the quote character.
  1204. // *Keeps quote char* to value to get_QuoteChar() correctly.
  1205. private string ReadAttribute (bool isDefaultValue)
  1206. {
  1207. ClearValueBuffer ();
  1208. int quoteChar = ReadChar ();
  1209. if (quoteChar != '\'' && quoteChar != '\"')
  1210. throw new XmlException (this as IXmlLineInfo,"an attribute value was not quoted");
  1211. AppendValueChar (quoteChar);
  1212. while (PeekChar () != quoteChar) {
  1213. int ch = ReadChar ();
  1214. switch (ch)
  1215. {
  1216. case '<':
  1217. throw new XmlException (this as IXmlLineInfo,"attribute values cannot contain '<'");
  1218. case -1:
  1219. throw new XmlException (this as IXmlLineInfo,"unexpected end of file in an attribute value");
  1220. /*
  1221. case '&':
  1222. if (isDefaultValue) {
  1223. AppendValueChar (ch);
  1224. break;
  1225. }
  1226. AppendValueChar (ch);
  1227. if (PeekChar () == '#')
  1228. break;
  1229. // Check XML 1.0 section 3.1 WFC.
  1230. string entName = ReadName ();
  1231. Expect (';');
  1232. if (XmlChar.GetPredefinedEntity (entName) == 0) {
  1233. DTDEntityDeclaration entDecl =
  1234. DTD == null ? null : DTD.EntityDecls [entName];
  1235. if (entDecl == null || entDecl.SystemId != null)
  1236. throw new XmlException (this as IXmlLineInfo,
  1237. "Reference to external entities is not allowed in attribute value.");
  1238. }
  1239. valueBuffer.Append (entName);
  1240. AppendValueChar (';');
  1241. break;
  1242. */
  1243. default:
  1244. AppendValueChar (ch);
  1245. break;
  1246. }
  1247. }
  1248. ReadChar (); // quoteChar
  1249. AppendValueChar (quoteChar);
  1250. return CreateValueString ();
  1251. }
  1252. // The reader is positioned on the first character
  1253. // of the target.
  1254. //
  1255. // It may be xml declaration or processing instruction.
  1256. private void ReadProcessingInstruction ()
  1257. {
  1258. string target = ReadName ();
  1259. if (target == "xml") {
  1260. ReadXmlDeclaration ();
  1261. return;
  1262. } else if (target.ToLower () == "xml")
  1263. throw new XmlException (this as IXmlLineInfo,
  1264. "Not allowed processing instruction name which starts with 'X', 'M', 'L' was found.");
  1265. if (currentState == XmlNodeType.None)
  1266. currentState = XmlNodeType.XmlDeclaration;
  1267. if (!SkipWhitespace ())
  1268. if (PeekChar () != '?')
  1269. throw new XmlException (this as IXmlLineInfo,
  1270. "Invalid processing instruction name was found.");
  1271. ClearValueBuffer ();
  1272. while (PeekChar () != -1) {
  1273. int ch = ReadChar ();
  1274. if (ch == '?' && PeekChar () == '>') {
  1275. ReadChar ();
  1276. break;
  1277. }
  1278. AppendValueChar ((char)ch);
  1279. }
  1280. SetProperties (
  1281. XmlNodeType.ProcessingInstruction, // nodeType
  1282. target, // name
  1283. false, // isEmptyElement
  1284. valueBuffer, // value
  1285. true // clearAttributes
  1286. );
  1287. }
  1288. // The reader is positioned after "<?xml "
  1289. private void ReadXmlDeclaration ()
  1290. {
  1291. if (currentState != XmlNodeType.None) {
  1292. if (maybeTextDecl == 0)
  1293. throw new XmlException (this as IXmlLineInfo,
  1294. "XML declaration cannot appear in this state.");
  1295. }
  1296. // Is this required?
  1297. // if (maybeTextDecl != 0)
  1298. // currentState = XmlNodeType.XmlDeclaration;
  1299. ClearAttributes ();
  1300. ReadAttributes (true); // They must have "version."
  1301. string version = (string) attributes ["version"];
  1302. if (version != null)
  1303. version = version.Substring (1, version.Length - 2);
  1304. string message = null;
  1305. if (parserInputStack.Count == 0) {
  1306. if (maybeTextDecl == 0 && (orderedAttributes [0] as string != "version" || version != "1.0"))
  1307. message = "Version 1.0 declaration is required in XML Declaration.";
  1308. else if (orderedAttributes.Count > 1 &&
  1309. (orderedAttributes [1] as string != "encoding" &&
  1310. orderedAttributes [1] as string != "standalone"))
  1311. message = "Invalid Xml Declaration markup was found.";
  1312. else if (orderedAttributes.Count > 2 && orderedAttributes [2] as string != "standalone")
  1313. message = "Invalid Xml Declaration markup was found.";
  1314. string sa = attributes ["standalone"] as string;
  1315. if (sa != null)
  1316. sa = sa.Substring (1, sa.Length - 2);
  1317. if (sa != null && sa != "yes" && sa != "no")
  1318. message = "Only 'yes' or 'no' is allowed for standalone.";
  1319. this.isStandalone = (sa == "yes");
  1320. } else {
  1321. int currentCheck = 0;
  1322. if (orderedAttributes [0] as string == "version") {
  1323. if (version != "1.0")
  1324. message = "Version 1.0 declaration is required in Text Declaration.";
  1325. currentCheck = 1;
  1326. }
  1327. if (orderedAttributes.Count <= currentCheck || orderedAttributes [currentCheck] as string != "encoding")
  1328. message = "Invalid Text Declaration markup was found. encoding specification is required.";
  1329. }
  1330. if (message != null)
  1331. throw new XmlException (this as IXmlLineInfo, message);
  1332. Expect ("?>");
  1333. if (maybeTextDecl != 0)
  1334. if (this ["standalone"] != null)
  1335. throw new XmlException (this as IXmlLineInfo,
  1336. "Invalid text declaration.");
  1337. if (maybeTextDecl == 2)
  1338. maybeTextDecl = 1;
  1339. SetProperties (
  1340. XmlNodeType.XmlDeclaration, // nodeType
  1341. "xml", // name
  1342. false, // isEmptyElement
  1343. currentInput.CurrentMarkup.ToString (6, currentInput.CurrentMarkup.Length - 6), // value
  1344. false // clearAttributes
  1345. );
  1346. }
  1347. // The reader is positioned on the first character after
  1348. // the leading '<!'.
  1349. private void ReadDeclaration ()
  1350. {
  1351. int ch = PeekChar ();
  1352. switch (ch)
  1353. {
  1354. case '-':
  1355. Expect ("--");
  1356. ReadComment ();
  1357. break;
  1358. case '[':
  1359. ReadChar ();
  1360. Expect ("CDATA[");
  1361. ReadCDATA ();
  1362. break;
  1363. case 'D':
  1364. Expect ("DOCTYPE");
  1365. ReadDoctypeDecl ();
  1366. break;
  1367. default:
  1368. throw new XmlException (this as IXmlLineInfo,
  1369. "Unexpected declaration markup was found.");
  1370. }
  1371. }
  1372. // The reader is positioned on the first character after
  1373. // the leading '<!--'.
  1374. private void ReadComment ()
  1375. {
  1376. if (currentState == XmlNodeType.None)
  1377. currentState = XmlNodeType.XmlDeclaration;
  1378. ClearValueBuffer ();
  1379. while (PeekChar () != -1) {
  1380. int ch = ReadChar ();
  1381. if (ch == '-' && PeekChar () == '-') {
  1382. ReadChar ();
  1383. if (PeekChar () != '>')
  1384. throw new XmlException (this as IXmlLineInfo,"comments cannot contain '--'");
  1385. ReadChar ();
  1386. break;
  1387. }
  1388. if (XmlConstructs.IsInvalid (ch))
  1389. throw new XmlException (this as IXmlLineInfo,
  1390. "Not allowed character was found.");
  1391. AppendValueChar ((char)ch);
  1392. }
  1393. SetProperties (
  1394. XmlNodeType.Comment, // nodeType
  1395. String.Empty, // name
  1396. false, // isEmptyElement
  1397. valueBuffer, // value
  1398. true // clearAttributes
  1399. );
  1400. }
  1401. // The reader is positioned on the first character after
  1402. // the leading '<![CDATA['.
  1403. private void ReadCDATA ()
  1404. {
  1405. if (currentState != XmlNodeType.Element)
  1406. throw new XmlException (this as IXmlLineInfo,
  1407. "CDATA section cannot appear in this state.");
  1408. ClearValueBuffer ();
  1409. bool skip = false;
  1410. int ch = 0;
  1411. while (PeekChar () != -1) {
  1412. if (!skip)
  1413. ch = ReadChar ();
  1414. skip = false;
  1415. if (ch == ']' && PeekChar () == ']') {
  1416. ch = ReadChar (); // ']'
  1417. if (PeekChar () == '>') {
  1418. ReadChar (); // '>'
  1419. break;
  1420. } else {
  1421. skip = true;
  1422. // AppendValueChar (']');
  1423. // AppendValueChar (']');
  1424. // ch = ReadChar ();
  1425. }
  1426. }
  1427. AppendValueChar ((char)ch);
  1428. }
  1429. SetProperties (
  1430. XmlNodeType.CDATA, // nodeType
  1431. String.Empty, // name
  1432. false, // isEmptyElement
  1433. valueBuffer, // value
  1434. true // clearAttributes
  1435. );
  1436. }
  1437. // The reader is positioned on the first character after
  1438. // the leading '<!DOCTYPE'.
  1439. private void ReadDoctypeDecl ()
  1440. {
  1441. switch (currentState) {
  1442. case XmlNodeType.DocumentType:
  1443. case XmlNodeType.Element:
  1444. case XmlNodeType.EndElement:
  1445. throw new XmlException (this as IXmlLineInfo,
  1446. "Document type cannot appear in this state.");
  1447. }
  1448. currentState = XmlNodeType.DocumentType;
  1449. string doctypeName = null;
  1450. string publicId = null;
  1451. string systemId = null;
  1452. int intSubsetStartLine = 0;
  1453. int intSubsetStartColumn = 0;
  1454. SkipWhitespace ();
  1455. doctypeName = ReadName ();
  1456. SkipWhitespace ();
  1457. switch(PeekChar ())
  1458. {
  1459. case 'S':
  1460. systemId = ReadSystemLiteral (true);
  1461. break;
  1462. case 'P':
  1463. publicId = ReadPubidLiteral ();
  1464. if (!SkipWhitespace ())
  1465. throw new XmlException (this as IXmlLineInfo,
  1466. "Whitespace is required between PUBLIC id and SYSTEM id.");
  1467. systemId = ReadSystemLiteral (false);
  1468. break;
  1469. }
  1470. SkipWhitespace ();
  1471. if(PeekChar () == '[')
  1472. {
  1473. // read markupdecl etc. or end of decl
  1474. ReadChar ();
  1475. intSubsetStartLine = this.LineNumber;
  1476. intSubsetStartColumn = this.LinePosition;
  1477. int startPos = currentTag.Length;
  1478. ReadInternalSubset ();
  1479. int endPos = currentTag.Length - 1;
  1480. parserContext.InternalSubset = currentTag.ToString (startPos, endPos - startPos);
  1481. }
  1482. // end of DOCTYPE decl.
  1483. SkipWhitespace ();
  1484. Expect ('>');
  1485. GenerateDTDObjectModel (doctypeName, publicId,
  1486. systemId, parserContext.InternalSubset,
  1487. intSubsetStartLine, intSubsetStartColumn);
  1488. // set properties for <!DOCTYPE> node
  1489. SetProperties (
  1490. XmlNodeType.DocumentType, // nodeType
  1491. doctypeName, // name
  1492. false, // isEmptyElement
  1493. parserContext.InternalSubset, // value
  1494. true // clearAttributes
  1495. );
  1496. }
  1497. internal DTDObjectModel GenerateDTDObjectModel (string name, string publicId,
  1498. string systemId, string internalSubset)
  1499. {
  1500. return GenerateDTDObjectModel (name, publicId, systemId, internalSubset, 0, 0);
  1501. }
  1502. internal DTDObjectModel GenerateDTDObjectModel (string name, string publicId,
  1503. string systemId, string internalSubset, int intSubsetStartLine, int intSubsetStartColumn)
  1504. {
  1505. // now compile DTD
  1506. parserContext.Dtd = new DTDObjectModel (); // merges both internal and external subsets in the meantime,
  1507. DTD.BaseURI = BaseURI;
  1508. DTD.Name = name;
  1509. DTD.PublicId = publicId;
  1510. DTD.SystemId = systemId;
  1511. DTD.InternalSubset = internalSubset;
  1512. DTD.XmlResolver = resolver;
  1513. int originalParserDepth = parserInputStack.Count;
  1514. if (internalSubset != null && internalSubset.Length > 0) {
  1515. XmlParserInput original = currentInput;
  1516. currentInput = new XmlParserInput (new StringReader (internalSubset), BaseURI, intSubsetStartLine, intSubsetStartColumn);
  1517. do {
  1518. CompileDTDSubset ();
  1519. if (PeekChar () == -1 && parserInputStack.Count > 0)
  1520. PopParserInput ();
  1521. } while (nodeType != XmlNodeType.None || parserInputStack.Count > originalParserDepth);
  1522. if (dtdIncludeSect != 0)
  1523. throw new XmlException (this as IXmlLineInfo,"INCLUDE section is not ended correctly.");
  1524. currentInput = original;
  1525. }
  1526. if (systemId != null && systemId != String.Empty && resolver != null) {
  1527. PushParserInput (systemId);
  1528. do {
  1529. this.CompileDTDSubset ();
  1530. if (PeekChar () == -1 && parserInputStack.Count > 1)
  1531. PopParserInput ();
  1532. } while (nodeType != XmlNodeType.None || parserInputStack.Count > originalParserDepth + 1);
  1533. PopParserInput ();
  1534. }
  1535. return DTD;
  1536. }
  1537. private void PushParserInput (string url)
  1538. {
  1539. Uri baseUri = null;
  1540. try {
  1541. baseUri = new Uri (BaseURI);
  1542. } catch (UriFormatException) {
  1543. }
  1544. Uri absUri = resolver.ResolveUri (baseUri, url);
  1545. string absPath = absUri.ToString ();
  1546. foreach (XmlParserInput i in parserInputStack.ToArray ()) {
  1547. if (i.BaseURI == absPath)
  1548. throw new XmlException (this as IXmlLineInfo, "Nested inclusion is not allowed: " + url);
  1549. }
  1550. parserInputStack.Push (currentInput);
  1551. currentInput = new XmlParserInput (new XmlStreamReader (url, false, resolver, BaseURI), absPath);
  1552. parserContext.PushScope ();
  1553. parserContext.BaseURI = absPath;
  1554. maybeTextDecl = 2;
  1555. }
  1556. private void PopParserInput ()
  1557. {
  1558. currentInput = parserInputStack.Pop () as XmlParserInput;
  1559. parserContext.PopScope ();
  1560. }
  1561. private enum DtdInputState
  1562. {
  1563. Free = 1,
  1564. ElementDecl,
  1565. AttlistDecl,
  1566. EntityDecl,
  1567. NotationDecl,
  1568. PI,
  1569. Comment,
  1570. InsideSingleQuoted,
  1571. InsideDoubleQuoted,
  1572. }
  1573. private class DtdInputStateStack
  1574. {
  1575. Stack intern = new Stack ();
  1576. public DtdInputStateStack ()
  1577. {
  1578. Push (DtdInputState.Free);
  1579. }
  1580. public DtdInputState Peek ()
  1581. {
  1582. return (DtdInputState) intern.Peek ();
  1583. }
  1584. public DtdInputState Pop ()
  1585. {
  1586. return (DtdInputState) intern.Pop ();
  1587. }
  1588. public void Push (DtdInputState val)
  1589. {
  1590. intern.Push (val);
  1591. }
  1592. }
  1593. DtdInputStateStack stateStack = new DtdInputStateStack ();
  1594. DtdInputState State {
  1595. get { return stateStack.Peek (); }
  1596. }
  1597. // Simply read but not generate any result.
  1598. private void ReadInternalSubset ()
  1599. {
  1600. bool continueParse = true;
  1601. while (continueParse) {
  1602. switch (ReadChar ()) {
  1603. case ']':
  1604. switch (State) {
  1605. case DtdInputState.Free:
  1606. continueParse = false;
  1607. break;
  1608. case DtdInputState.InsideDoubleQuoted:
  1609. continue;
  1610. case DtdInputState.InsideSingleQuoted:
  1611. continue;
  1612. default:
  1613. throw new XmlException (this as IXmlLineInfo,"unexpected end of file at DTD.");
  1614. }
  1615. break;
  1616. case -1:
  1617. throw new XmlException (this as IXmlLineInfo,"unexpected end of file at DTD.");
  1618. case '<':
  1619. if (State == DtdInputState.InsideDoubleQuoted ||
  1620. State == DtdInputState.InsideSingleQuoted)
  1621. continue; // well-formed
  1622. switch (ReadChar ()) {
  1623. case '?':
  1624. stateStack.Push (DtdInputState.PI);
  1625. break;
  1626. case '!':
  1627. switch (ReadChar ()) {
  1628. case 'E':
  1629. switch (ReadChar ()) {
  1630. case 'L':
  1631. Expect ("EMENT");
  1632. stateStack.Push (DtdInputState.ElementDecl);
  1633. break;
  1634. case 'N':
  1635. Expect ("TITY");
  1636. stateStack.Push (DtdInputState.EntityDecl);
  1637. break;
  1638. default:
  1639. throw new XmlException (this as IXmlLineInfo,"unexpected token '<!E'.");
  1640. }
  1641. break;
  1642. case 'A':
  1643. Expect ("TTLIST");
  1644. stateStack.Push (DtdInputState.AttlistDecl);
  1645. break;
  1646. case 'N':
  1647. Expect ("OTATION");
  1648. stateStack.Push (DtdInputState.NotationDecl);
  1649. break;
  1650. case '-':
  1651. Expect ("-");
  1652. stateStack.Push (DtdInputState.Comment);
  1653. break;
  1654. }
  1655. break;
  1656. default:
  1657. throw new XmlException (this as IXmlLineInfo,"unexpected '>'.");
  1658. }
  1659. break;
  1660. case '\'':
  1661. if (State == DtdInputState.InsideSingleQuoted)
  1662. stateStack.Pop ();
  1663. else if (State != DtdInputState.InsideDoubleQuoted && State != DtdInputState.Comment)
  1664. stateStack.Push (DtdInputState.InsideSingleQuoted);
  1665. break;
  1666. case '"':
  1667. if (State == DtdInputState.InsideDoubleQuoted)
  1668. stateStack.Pop ();
  1669. else if (State != DtdInputState.InsideSingleQuoted && State != DtdInputState.Comment)
  1670. stateStack.Push (DtdInputState.InsideDoubleQuoted);
  1671. break;
  1672. case '>':
  1673. switch (State) {
  1674. case DtdInputState.ElementDecl:
  1675. goto case DtdInputState.NotationDecl;
  1676. case DtdInputState.AttlistDecl:
  1677. goto case DtdInputState.NotationDecl;
  1678. case DtdInputState.EntityDecl:
  1679. goto case DtdInputState.NotationDecl;
  1680. case DtdInputState.NotationDecl:
  1681. stateStack.Pop ();
  1682. break;
  1683. case DtdInputState.InsideDoubleQuoted:
  1684. continue;
  1685. case DtdInputState.InsideSingleQuoted:
  1686. continue; // well-formed
  1687. case DtdInputState.Comment:
  1688. continue;
  1689. default:
  1690. throw new XmlException (this as IXmlLineInfo,"unexpected token '>'");
  1691. }
  1692. break;
  1693. case '?':
  1694. if (State == DtdInputState.PI) {
  1695. if (ReadChar () == '>')
  1696. stateStack.Pop ();
  1697. }
  1698. break;
  1699. case '-':
  1700. if (State == DtdInputState.Comment) {
  1701. if (PeekChar () == '-') {
  1702. ReadChar ();
  1703. Expect ('>');
  1704. stateStack.Pop ();
  1705. }
  1706. }
  1707. break;
  1708. case '%':
  1709. if (State != DtdInputState.Free && State != DtdInputState.EntityDecl && State != DtdInputState.Comment && State != DtdInputState.InsideDoubleQuoted && State != DtdInputState.InsideSingleQuoted)
  1710. throw new XmlException (this as IXmlLineInfo,"Parameter Entity Reference cannot appear as a part of markupdecl (see XML spec 2.8).");
  1711. break;
  1712. }
  1713. }
  1714. }
  1715. // Read any one of following:
  1716. // elementdecl, AttlistDecl, EntityDecl, NotationDecl,
  1717. // PI, Comment, Parameter Entity, or doctype termination char(']')
  1718. //
  1719. // returns a node of some nodeType or null, setting nodeType.
  1720. // (if None then ']' was found.)
  1721. private void CompileDTDSubset()
  1722. {
  1723. SkipWhitespace ();
  1724. switch(PeekChar ())
  1725. {
  1726. case -1:
  1727. nodeType = XmlNodeType.None;
  1728. break;
  1729. case '%':
  1730. // It affects on entity references' well-formedness
  1731. if (this.parserInputStack.Count == 0)
  1732. DTD.InternalSubsetHasPEReference = true;
  1733. ReadChar ();
  1734. string peName = ReadName ();
  1735. Expect (';');
  1736. currentInput.InsertParameterEntityBuffer (GetPEValue (peName));
  1737. int currentLine = currentInput.LineNumber;
  1738. int currentColumn = currentInput.LinePosition;
  1739. while (currentInput.HasPEBuffer)
  1740. CompileDTDSubset ();
  1741. if (currentInput.LineNumber != currentLine ||
  1742. currentInput.LinePosition != currentColumn)
  1743. throw new XmlException (this as IXmlLineInfo,
  1744. "Incorrectly nested parameter entity.");
  1745. break;
  1746. case '<':
  1747. ReadChar ();
  1748. switch(ReadChar ())
  1749. {
  1750. case '?':
  1751. // Only read, no store.
  1752. ReadProcessingInstruction ();
  1753. break;
  1754. case '!':
  1755. CompileDeclaration ();
  1756. break;
  1757. default:
  1758. throw new XmlException (this as IXmlLineInfo,"Syntax Error after '<' character.");
  1759. }
  1760. break;
  1761. case ']':
  1762. if (dtdIncludeSect == 0)
  1763. throw new XmlException (this as IXmlLineInfo, "Unbalanced end of INCLUDE/IGNORE section.");
  1764. // End of inclusion
  1765. Expect ("]]>");
  1766. dtdIncludeSect--;
  1767. SkipWhitespace ();
  1768. break;
  1769. default:
  1770. throw new XmlException (this as IXmlLineInfo,String.Format ("Syntax Error inside doctypedecl markup : {0}({1})", PeekChar (), (char) PeekChar ()));
  1771. }
  1772. }
  1773. private void CompileDeclaration ()
  1774. {
  1775. nodeType = XmlNodeType.DocumentType; // Hack!!
  1776. switch(ReadChar ())
  1777. {
  1778. case '-':
  1779. Expect ('-');
  1780. // Only read, no store.
  1781. ReadComment ();
  1782. break;
  1783. case 'E':
  1784. switch(ReadChar ())
  1785. {
  1786. case 'N':
  1787. Expect ("TITY");
  1788. if (!SkipWhitespace ())
  1789. throw new XmlException (this as IXmlLineInfo,
  1790. "Whitespace is required after '<!ENTITY' in DTD entity declaration.");
  1791. LOOPBACK:
  1792. if (PeekChar () == '%') {
  1793. ReadChar ();
  1794. if (!SkipWhitespace ()) {
  1795. ImportAsPERef ();
  1796. goto LOOPBACK;
  1797. } else {
  1798. TryExpandPERef ();
  1799. SkipWhitespace ();
  1800. if (XmlChar.IsNameChar (PeekChar ()))
  1801. ReadParameterEntityDecl ();
  1802. else
  1803. throw new XmlException (this as IXmlLineInfo,"expected name character");
  1804. }
  1805. break;
  1806. }
  1807. DTDEntityDeclaration ent = ReadEntityDecl ();
  1808. if (DTD.EntityDecls [ent.Name] == null)
  1809. DTD.EntityDecls.Add (ent.Name, ent);
  1810. break;
  1811. case 'L':
  1812. Expect ("EMENT");
  1813. DTDElementDeclaration el = ReadElementDecl ();
  1814. DTD.ElementDecls.Add (el.Name, el);
  1815. break;
  1816. default:
  1817. throw new XmlException (this as IXmlLineInfo,"Syntax Error after '<!E' (ELEMENT or ENTITY must be found)");
  1818. }
  1819. break;
  1820. case 'A':
  1821. Expect ("TTLIST");
  1822. DTDAttListDeclaration atl = ReadAttListDecl ();
  1823. // if (DTD.AttListDecls.ContainsKey (atl.Name))
  1824. DTD.AttListDecls.Add (atl.Name, atl);
  1825. break;
  1826. case 'N':
  1827. Expect ("OTATION");
  1828. DTDNotationDeclaration not = ReadNotationDecl ();
  1829. DTD.NotationDecls.Add (not.Name, not);
  1830. break;
  1831. case '[':
  1832. // conditional sections
  1833. SkipWhitespace ();
  1834. TryExpandPERef ();
  1835. SkipWhitespace ();
  1836. Expect ('I');
  1837. switch (ReadChar ()) {
  1838. case 'N':
  1839. Expect ("CLUDE");
  1840. SkipWhitespace ();
  1841. Expect ('[');
  1842. dtdIncludeSect++;
  1843. break;
  1844. case 'G':
  1845. Expect ("NORE");
  1846. ReadIgnoreSect ();
  1847. break;
  1848. }
  1849. break;
  1850. default:
  1851. throw new XmlException (this as IXmlLineInfo,"Syntax Error after '<!' characters.");
  1852. }
  1853. }
  1854. private void ReadIgnoreSect ()
  1855. {
  1856. bool skip = false;
  1857. SkipWhitespace ();
  1858. Expect ('[');
  1859. int dtdIgnoreSect = 1;
  1860. while (dtdIgnoreSect > 0) {
  1861. switch (skip ? PeekChar () : ReadChar ()) {
  1862. case -1:
  1863. throw new XmlException (this as IXmlLineInfo,"Unexpected IGNORE section end.");
  1864. case '<':
  1865. if (ReadChar () == '!' && ReadChar () == '[')
  1866. dtdIgnoreSect++;
  1867. break;
  1868. case ']':
  1869. if (ReadChar () == ']') {
  1870. if (ReadChar () == '>')
  1871. dtdIgnoreSect--;
  1872. else
  1873. skip = true;
  1874. }
  1875. break;
  1876. }
  1877. skip = false;
  1878. }
  1879. }
  1880. // The reader is positioned on the head of the name.
  1881. private DTDElementDeclaration ReadElementDecl ()
  1882. {
  1883. DTDElementDeclaration decl = new DTDElementDeclaration (DTD);
  1884. if (!SkipWhitespace ())
  1885. throw new XmlException (this as IXmlLineInfo,
  1886. "Whitespace is required between '<!ELEMENT' and name in DTD element declaration.");
  1887. TryExpandPERef ();
  1888. SkipWhitespace ();
  1889. decl.Name = ReadName ();
  1890. if (!SkipWhitespace ())
  1891. throw new XmlException (this as IXmlLineInfo,
  1892. "Whitespace is required between name and content in DTD element declaration.");
  1893. TryExpandPERef ();
  1894. ReadContentSpec (decl);
  1895. SkipWhitespace ();
  1896. // This expanding is only allowed as a non-validating parser.
  1897. TryExpandPERef ();
  1898. SkipWhitespace ();
  1899. Expect ('>');
  1900. return decl;
  1901. }
  1902. // read 'children'(BNF) of contentspec
  1903. private void ReadContentSpec (DTDElementDeclaration decl)
  1904. {
  1905. TryExpandPERef ();
  1906. SkipWhitespace ();
  1907. switch(PeekChar ())
  1908. {
  1909. case 'E':
  1910. decl.IsEmpty = true;
  1911. Expect ("EMPTY");
  1912. break;
  1913. case 'A':
  1914. decl.IsAny = true;
  1915. Expect ("ANY");
  1916. break;
  1917. case '(':
  1918. DTDContentModel model = decl.ContentModel;
  1919. ReadChar ();
  1920. SkipWhitespace ();
  1921. TryExpandPERef ();
  1922. SkipWhitespace ();
  1923. if(PeekChar () == '#') {
  1924. // Mixed Contents. "#PCDATA" must appear first.
  1925. decl.IsMixedContent = true;
  1926. model.Occurence = DTDOccurence.ZeroOrMore;
  1927. model.OrderType = DTDContentOrderType.Or;
  1928. Expect ("#PCDATA");
  1929. SkipWhitespace ();
  1930. TryExpandPERef ();
  1931. SkipWhitespace ();
  1932. while(PeekChar () != ')') {
  1933. Expect('|');
  1934. SkipWhitespace ();
  1935. TryExpandPERef ();
  1936. SkipWhitespace ();
  1937. DTDContentModel elem = new DTDContentModel (DTD, decl.Name);
  1938. elem.ElementName = ReadName ();
  1939. model.ChildModels.Add (elem);
  1940. SkipWhitespace ();
  1941. TryExpandPERef ();
  1942. SkipWhitespace ();
  1943. }
  1944. Expect (')');
  1945. if (model.ChildModels.Count > 0)
  1946. Expect ('*');
  1947. else if (PeekChar () == '*')
  1948. Expect ('*');
  1949. } else {
  1950. // Non-Mixed Contents
  1951. model.ChildModels.Add (ReadCP (decl));
  1952. SkipWhitespace ();
  1953. do { // copied from ReadCP() ...;-)
  1954. TryExpandPERef ();
  1955. SkipWhitespace ();
  1956. if(PeekChar ()=='|') {
  1957. // CPType=Or
  1958. if (model.OrderType == DTDContentOrderType.Seq)
  1959. throw new XmlException (this as IXmlLineInfo,
  1960. "Inconsistent choice markup in sequence cp.");
  1961. model.OrderType = DTDContentOrderType.Or;
  1962. ReadChar ();
  1963. SkipWhitespace ();
  1964. model.ChildModels.Add (ReadCP (decl));
  1965. SkipWhitespace ();
  1966. }
  1967. else if(PeekChar () == ',')
  1968. {
  1969. // CPType=Seq
  1970. if (model.OrderType == DTDContentOrderType.Or)
  1971. throw new XmlException (this as IXmlLineInfo,
  1972. "Inconsistent sequence markup in choice cp.");
  1973. model.OrderType = DTDContentOrderType.Seq;
  1974. ReadChar ();
  1975. SkipWhitespace ();
  1976. model.ChildModels.Add (ReadCP (decl));
  1977. SkipWhitespace ();
  1978. }
  1979. else
  1980. break;
  1981. }
  1982. while(true);
  1983. Expect (')');
  1984. switch(PeekChar ())
  1985. {
  1986. case '?':
  1987. model.Occurence = DTDOccurence.Optional;
  1988. ReadChar ();
  1989. break;
  1990. case '*':
  1991. model.Occurence = DTDOccurence.ZeroOrMore;
  1992. ReadChar ();
  1993. break;
  1994. case '+':
  1995. model.Occurence = DTDOccurence.OneOrMore;
  1996. ReadChar ();
  1997. break;
  1998. }
  1999. SkipWhitespace ();
  2000. }
  2001. SkipWhitespace ();
  2002. break;
  2003. }
  2004. }
  2005. // Read 'cp' (BNF) of contentdecl (BNF)
  2006. private DTDContentModel ReadCP (DTDElementDeclaration elem)
  2007. {
  2008. DTDContentModel model = null;
  2009. TryExpandPERef ();
  2010. SkipWhitespace ();
  2011. if(PeekChar () == '(') {
  2012. model = new DTDContentModel (DTD, elem.Name);
  2013. ReadChar ();
  2014. SkipWhitespace ();
  2015. model.ChildModels.Add (ReadCP (elem));
  2016. SkipWhitespace ();
  2017. do {
  2018. TryExpandPERef ();
  2019. SkipWhitespace ();
  2020. if(PeekChar ()=='|') {
  2021. // CPType=Or
  2022. if (model.OrderType == DTDContentOrderType.Seq)
  2023. throw new XmlException (this as IXmlLineInfo,
  2024. "Inconsistent choice markup in sequence cp.");
  2025. model.OrderType = DTDContentOrderType.Or;
  2026. ReadChar ();
  2027. SkipWhitespace ();
  2028. model.ChildModels.Add (ReadCP (elem));
  2029. SkipWhitespace ();
  2030. }
  2031. else if(PeekChar () == ',') {
  2032. // CPType=Seq
  2033. if (model.OrderType == DTDContentOrderType.Or)
  2034. throw new XmlException (this as IXmlLineInfo,
  2035. "Inconsistent sequence markup in choice cp.");
  2036. model.OrderType = DTDContentOrderType.Seq;
  2037. ReadChar ();
  2038. SkipWhitespace ();
  2039. model.ChildModels.Add (ReadCP (elem));
  2040. SkipWhitespace ();
  2041. }
  2042. else
  2043. break;
  2044. }
  2045. while(true);
  2046. SkipWhitespace ();
  2047. Expect (')');
  2048. }
  2049. else {
  2050. TryExpandPERef ();
  2051. model = new DTDContentModel (DTD, elem.Name);
  2052. SkipWhitespace ();
  2053. model.ElementName = ReadName ();
  2054. }
  2055. switch(PeekChar ()) {
  2056. case '?':
  2057. model.Occurence = DTDOccurence.Optional;
  2058. ReadChar ();
  2059. break;
  2060. case '*':
  2061. model.Occurence = DTDOccurence.ZeroOrMore;
  2062. ReadChar ();
  2063. break;
  2064. case '+':
  2065. model.Occurence = DTDOccurence.OneOrMore;
  2066. ReadChar ();
  2067. break;
  2068. }
  2069. return model;
  2070. }
  2071. // The reader is positioned on the first name char.
  2072. private void ReadParameterEntityDecl ()
  2073. {
  2074. DTDParameterEntityDeclaration decl =
  2075. new DTDParameterEntityDeclaration();
  2076. decl.BaseURI = BaseURI;
  2077. decl.Name = ReadName ();
  2078. if (!SkipWhitespace ())
  2079. throw new XmlException (this as IXmlLineInfo,
  2080. "Whitespace is required after name in DTD parameter entity declaration.");
  2081. if (PeekChar () == 'S' || PeekChar () == 'P') {
  2082. // throw new NotImplementedException ("External parameter entity reference is not implemented yet.");
  2083. // read publicId/systemId
  2084. ReadExternalID ();
  2085. decl.PublicId = attributes ["PUBLIC"] as string;
  2086. decl.SystemId = attributes ["SYSTEM"] as string;
  2087. SkipWhitespace ();
  2088. decl.Resolve (resolver);
  2089. }
  2090. else {
  2091. TryExpandPERef ();
  2092. int quoteChar = ReadChar ();
  2093. int start = currentTag.Length;
  2094. ClearValueBuffer ();
  2095. bool loop = true;
  2096. while (loop) {
  2097. int c = PeekChar ();
  2098. switch (c) {
  2099. case -1:
  2100. throw new XmlException ("unexpected end of stream in entity value definition.");
  2101. case '"':
  2102. ReadChar ();
  2103. if (quoteChar == '"')
  2104. loop = false;
  2105. else
  2106. AppendValueChar ('"');
  2107. break;
  2108. case '\'':
  2109. ReadChar ();
  2110. if (quoteChar == '\'')
  2111. loop = false;
  2112. else
  2113. AppendValueChar ('\'');
  2114. break;
  2115. case '&':
  2116. ReadChar ();
  2117. if (PeekChar () == '#') {
  2118. ReadChar ();
  2119. ReadCharacterReference ();
  2120. }
  2121. else
  2122. AppendValueChar ('&');
  2123. break;
  2124. case '%':
  2125. ReadChar ();
  2126. string peName = ReadName ();
  2127. Expect (';');
  2128. valueBuffer.Append (GetPEValue (peName));
  2129. break;
  2130. default:
  2131. AppendValueChar (ReadChar ());
  2132. break;
  2133. }
  2134. }
  2135. decl.LiteralValue = CreateValueString (); // currentTag.ToString (start, currentTag.Length - start - 1);
  2136. ClearValueBuffer ();
  2137. }
  2138. SkipWhitespace ();
  2139. Expect ('>');
  2140. if (parameterEntities [decl.Name] == null) {
  2141. parameterEntities.Add (decl.Name, decl);
  2142. }
  2143. }
  2144. private string GetPEValue (string peName)
  2145. {
  2146. DTDParameterEntityDeclaration peDecl =
  2147. this.parameterEntities [peName] as DTDParameterEntityDeclaration;
  2148. if (peDecl != null)
  2149. return peDecl.Value;
  2150. // See XML 1.0 section 4.1 for both WFC and VC.
  2151. if ((DTD.SystemId == null && !DTD.InternalSubsetHasPEReference) || this.isStandalone)
  2152. throw new XmlException (this as IXmlLineInfo,
  2153. "Parameter entity " + peName + " not found.");
  2154. DTD.AddError (new XmlSchemaException (
  2155. "Parameter entity " + peName + " not found.", null));
  2156. return "";
  2157. }
  2158. private void TryExpandPERef ()
  2159. {
  2160. if (PeekChar () == '%') {
  2161. // ReadChar ();
  2162. // if (!XmlChar.IsNameChar (PeekChar ()))
  2163. // return;
  2164. // ExpandPERef ();
  2165. ImportAsPERef ();
  2166. }
  2167. }
  2168. // reader is positioned on '%'
  2169. private void ImportAsPERef ()
  2170. {
  2171. ReadChar ();
  2172. string peName = ReadName ();
  2173. Expect (';');
  2174. DTDParameterEntityDeclaration peDecl =
  2175. this.parameterEntities [peName] as DTDParameterEntityDeclaration;
  2176. if (peDecl == null) {
  2177. DTD.AddError (new XmlSchemaException ("Parameter entity " + peName + " not found.", null));
  2178. return; // do nothing
  2179. }
  2180. currentInput.InsertParameterEntityBuffer (" " + peDecl.Value + " ");
  2181. }
  2182. // The reader is positioned on the head of the name.
  2183. private DTDEntityDeclaration ReadEntityDecl ()
  2184. {
  2185. DTDEntityDeclaration decl = new DTDEntityDeclaration (DTD);
  2186. decl.IsInternalSubset = (parserInputStack.Count == 0);
  2187. TryExpandPERef ();
  2188. SkipWhitespace ();
  2189. decl.Name = ReadName ();
  2190. if (!SkipWhitespace ())
  2191. throw new XmlException (this as IXmlLineInfo,
  2192. "Whitespace is required between name and content in DTD entity declaration.");
  2193. TryExpandPERef ();
  2194. SkipWhitespace ();
  2195. if (PeekChar () == 'S' || PeekChar () == 'P') {
  2196. // external entity
  2197. ReadExternalID ();
  2198. decl.PublicId = attributes ["PUBLIC"] as string;
  2199. decl.SystemId = attributes ["SYSTEM"] as string;
  2200. if (SkipWhitespace ()) {
  2201. if (PeekChar () == 'N') {
  2202. // NDataDecl
  2203. Expect ("NDATA");
  2204. if (!SkipWhitespace ())
  2205. throw new XmlException (this as IXmlLineInfo,
  2206. "Whitespace is required after NDATA.");
  2207. decl.NotationName = ReadName (); // ndata_name
  2208. }
  2209. }
  2210. }
  2211. else {
  2212. // literal entity
  2213. ReadEntityValueDecl (decl);
  2214. }
  2215. SkipWhitespace ();
  2216. // This expanding is only allowed as a non-validating parser.
  2217. TryExpandPERef ();
  2218. SkipWhitespace ();
  2219. Expect ('>');
  2220. return decl;
  2221. }
  2222. private void ReadEntityValueDecl (DTDEntityDeclaration decl)
  2223. {
  2224. SkipWhitespace ();
  2225. // quotation char will be finally removed on unescaping
  2226. int quoteChar = ReadChar ();
  2227. int start = currentTag.Length;
  2228. if (quoteChar != '\'' && quoteChar != '"')
  2229. throw new XmlException ("quotation char was expected.");
  2230. ClearValueBuffer ();
  2231. while (PeekChar () != quoteChar) {
  2232. switch (PeekChar ()) {
  2233. case '%':
  2234. ReadChar ();
  2235. string name = ReadName ();
  2236. Expect (';');
  2237. if (decl.IsInternalSubset)
  2238. throw new XmlException (this as IXmlLineInfo,
  2239. "Parameter entity is not allowed in internal subset entity '" + name + "'");
  2240. valueBuffer.Append (GetPEValue (name));
  2241. break;
  2242. case -1:
  2243. throw new XmlException ("unexpected end of stream.");
  2244. default:
  2245. AppendValueChar (ReadChar ());
  2246. break;
  2247. }
  2248. }
  2249. // string value = Dereference (currentTag.ToString (start, currentTag.Length - start), false);
  2250. string value = Dereference (CreateValueString (), false);
  2251. ClearValueBuffer ();
  2252. Expect (quoteChar);
  2253. decl.LiteralEntityValue = value;
  2254. }
  2255. private DTDAttListDeclaration ReadAttListDecl ()
  2256. {
  2257. SkipWhitespace ();
  2258. TryExpandPERef ();
  2259. SkipWhitespace ();
  2260. string name = ReadName (); // target element name
  2261. DTDAttListDeclaration decl =
  2262. DTD.AttListDecls [name] as DTDAttListDeclaration;
  2263. if (decl == null)
  2264. decl = new DTDAttListDeclaration (DTD);
  2265. decl.Name = name;
  2266. if (!SkipWhitespace ())
  2267. if (PeekChar () != '>')
  2268. throw new XmlException (this as IXmlLineInfo,
  2269. "Whitespace is required between name and content in non-empty DTD attlist declaration.");
  2270. TryExpandPERef ();
  2271. SkipWhitespace ();
  2272. while (XmlChar.IsNameChar ((char) PeekChar ())) {
  2273. DTDAttributeDefinition def = ReadAttributeDefinition ();
  2274. if (decl [def.Name] == null)
  2275. decl.Add (def);
  2276. SkipWhitespace ();
  2277. TryExpandPERef ();
  2278. SkipWhitespace ();
  2279. }
  2280. SkipWhitespace ();
  2281. // This expanding is only allowed as a non-validating parser.
  2282. TryExpandPERef ();
  2283. SkipWhitespace ();
  2284. Expect ('>');
  2285. return decl;
  2286. }
  2287. private DTDAttributeDefinition ReadAttributeDefinition ()
  2288. {
  2289. DTDAttributeDefinition def = new DTDAttributeDefinition ();
  2290. // attr_name
  2291. TryExpandPERef ();
  2292. SkipWhitespace ();
  2293. def.Name = ReadName ();
  2294. if (!SkipWhitespace ())
  2295. throw new XmlException (this as IXmlLineInfo,
  2296. "Whitespace is required between name and content in DTD attribute definition.");
  2297. // attr_value
  2298. TryExpandPERef ();
  2299. SkipWhitespace ();
  2300. switch(PeekChar ()) {
  2301. case 'C': // CDATA
  2302. Expect ("CDATA");
  2303. def.Datatype = XmlSchemaDatatype.FromName ("normalizedString");
  2304. break;
  2305. case 'I': // ID, IDREF, IDREFS
  2306. Expect ("ID");
  2307. if(PeekChar () == 'R') {
  2308. Expect ("REF");
  2309. if(PeekChar () == 'S') {
  2310. // IDREFS
  2311. ReadChar ();
  2312. def.Datatype = XmlSchemaDatatype.FromName ("IDREFS");
  2313. }
  2314. else // IDREF
  2315. def.Datatype = XmlSchemaDatatype.FromName ("IDREF");
  2316. }
  2317. else // ID
  2318. def.Datatype = XmlSchemaDatatype.FromName ("ID");
  2319. break;
  2320. case 'E': // ENTITY, ENTITIES
  2321. Expect ("ENTIT");
  2322. switch(ReadChar ()) {
  2323. case 'Y': // ENTITY
  2324. def.Datatype = XmlSchemaDatatype.FromName ("ENTITY");
  2325. break;
  2326. case 'I': // ENTITIES
  2327. Expect ("ES");
  2328. def.Datatype = XmlSchemaDatatype.FromName ("ENTITIES");
  2329. break;
  2330. }
  2331. break;
  2332. case 'N': // NMTOKEN, NMTOKENS, NOTATION
  2333. ReadChar ();
  2334. switch(PeekChar ()) {
  2335. case 'M':
  2336. Expect ("MTOKEN");
  2337. if(PeekChar ()=='S') { // NMTOKENS
  2338. ReadChar ();
  2339. def.Datatype = XmlSchemaDatatype.FromName ("NMTOKENS");
  2340. }
  2341. else // NMTOKEN
  2342. def.Datatype = XmlSchemaDatatype.FromName ("NMTOKEN");
  2343. break;
  2344. case 'O':
  2345. Expect ("OTATION");
  2346. def.Datatype = XmlSchemaDatatype.FromName ("NOTATION");
  2347. if (!SkipWhitespace ())
  2348. throw new XmlException (this as IXmlLineInfo,
  2349. "Whitespace is required between name and content in DTD attribute definition.");
  2350. Expect ('(');
  2351. SkipWhitespace ();
  2352. def.EnumeratedNotations.Add (ReadName ()); // notation name
  2353. SkipWhitespace ();
  2354. while(PeekChar () == '|') {
  2355. ReadChar ();
  2356. SkipWhitespace ();
  2357. def.EnumeratedNotations.Add (ReadName ()); // notation name
  2358. SkipWhitespace ();
  2359. }
  2360. Expect (')');
  2361. break;
  2362. default:
  2363. throw new XmlException ("attribute declaration syntax error.");
  2364. }
  2365. break;
  2366. default: // Enumerated Values
  2367. def.Datatype = XmlSchemaDatatype.FromName ("NMTOKEN");
  2368. TryExpandPERef ();
  2369. SkipWhitespace ();
  2370. Expect ('(');
  2371. SkipWhitespace ();
  2372. def.EnumeratedAttributeDeclaration.Add (
  2373. def.Datatype.Normalize (ReadNmToken ())); // enum value
  2374. SkipWhitespace ();
  2375. while(PeekChar () == '|') {
  2376. ReadChar ();
  2377. SkipWhitespace ();
  2378. def.EnumeratedAttributeDeclaration.Add (
  2379. def.Datatype.Normalize (ReadNmToken ())); // enum value
  2380. SkipWhitespace ();
  2381. }
  2382. Expect (')');
  2383. break;
  2384. }
  2385. TryExpandPERef ();
  2386. if (!SkipWhitespace ())
  2387. throw new XmlException (this as IXmlLineInfo,
  2388. "Whitespace is required between type and occurence in DTD attribute definition.");
  2389. // def_value
  2390. if(PeekChar () == '#')
  2391. {
  2392. ReadChar ();
  2393. switch(PeekChar ())
  2394. {
  2395. case 'R':
  2396. Expect ("REQUIRED");
  2397. def.OccurenceType = DTDAttributeOccurenceType.Required;
  2398. break;
  2399. case 'I':
  2400. Expect ("IMPLIED");
  2401. def.OccurenceType = DTDAttributeOccurenceType.Optional;
  2402. break;
  2403. case 'F':
  2404. Expect ("FIXED");
  2405. def.OccurenceType = DTDAttributeOccurenceType.Fixed;
  2406. if (!SkipWhitespace ())
  2407. throw new XmlException (this as IXmlLineInfo,
  2408. "Whitespace is required between FIXED and actual value in DTD attribute definition.");
  2409. def.UnresolvedDefaultValue = ReadAttribute (true);
  2410. break;
  2411. }
  2412. } else {
  2413. // one of the enumerated value
  2414. TryExpandPERef ();
  2415. SkipWhitespace ();
  2416. def.UnresolvedDefaultValue = ReadAttribute (true);
  2417. }
  2418. return def;
  2419. }
  2420. private DTDNotationDeclaration ReadNotationDecl()
  2421. {
  2422. DTDNotationDeclaration decl = new DTDNotationDeclaration ();
  2423. TryExpandPERef ();
  2424. SkipWhitespace ();
  2425. decl.Name = ReadName (); // notation name
  2426. if (namespaces) { // copy from SetProperties ;-)
  2427. int indexOfColon = decl.Name.IndexOf (':');
  2428. if (indexOfColon == -1) {
  2429. decl.Prefix = String.Empty;
  2430. decl.LocalName = decl.Name;
  2431. } else {
  2432. decl.Prefix = decl.Name.Substring (0, indexOfColon);
  2433. decl.LocalName = decl.Name.Substring (indexOfColon + 1);
  2434. }
  2435. } else {
  2436. decl.Prefix = String.Empty;
  2437. decl.LocalName = decl.Name;
  2438. }
  2439. SkipWhitespace ();
  2440. if(PeekChar () == 'P') {
  2441. decl.PublicId = ReadPubidLiteral ();
  2442. bool wsSkipped = SkipWhitespace ();
  2443. if (PeekChar () == '\'' || PeekChar () == '"') {
  2444. if (!wsSkipped)
  2445. throw new XmlException (this as IXmlLineInfo,
  2446. "Whitespace is required between public id and system id.");
  2447. decl.SystemId = ReadSystemLiteral (false);
  2448. SkipWhitespace ();
  2449. }
  2450. } else if(PeekChar () == 'S') {
  2451. decl.SystemId = ReadSystemLiteral (true);
  2452. SkipWhitespace ();
  2453. }
  2454. if(decl.PublicId == null && decl.SystemId == null)
  2455. throw new XmlException ("public or system declaration required for \"NOTATION\" declaration.");
  2456. // This expanding is only allowed as a non-validating parser.
  2457. TryExpandPERef ();
  2458. SkipWhitespace ();
  2459. Expect ('>');
  2460. return decl;
  2461. }
  2462. private void ReadExternalID() {
  2463. switch(PeekChar ()) {
  2464. case 'S':
  2465. attributes ["PUBLIC"] = null;
  2466. attributes ["SYSTEM"] = ReadSystemLiteral (true);
  2467. break;
  2468. case 'P':
  2469. attributes ["PUBLIC"] = ReadPubidLiteral ();
  2470. if (!SkipWhitespace ())
  2471. throw new XmlException (this as IXmlLineInfo,
  2472. "Whitespace is required between PUBLIC id and SYSTEM id.");
  2473. attributes ["SYSTEM"] = ReadSystemLiteral (false);
  2474. break;
  2475. }
  2476. }
  2477. // The reader is positioned on the first 'S' of "SYSTEM".
  2478. private string ReadSystemLiteral (bool expectSYSTEM)
  2479. {
  2480. if(expectSYSTEM) {
  2481. Expect ("SYSTEM");
  2482. if (!SkipWhitespace ())
  2483. throw new XmlException (this as IXmlLineInfo,
  2484. "Whitespace is required after 'SYSTEM'.");
  2485. }
  2486. else
  2487. SkipWhitespace ();
  2488. int quoteChar = ReadChar (); // apos or quot
  2489. int startPos = currentTag.Length;
  2490. int c = 0;
  2491. while(c != quoteChar) {
  2492. c = ReadChar ();
  2493. if(c < 0) throw new XmlException (this as IXmlLineInfo,"Unexpected end of stream in ExternalID.");
  2494. }
  2495. return currentTag.ToString (startPos, currentTag.Length - 1 - startPos);
  2496. }
  2497. private string ReadPubidLiteral()
  2498. {
  2499. Expect ("PUBLIC");
  2500. if (!SkipWhitespace ())
  2501. throw new XmlException (this as IXmlLineInfo,
  2502. "Whitespace is required after 'PUBLIC'.");
  2503. int quoteChar = ReadChar ();
  2504. int startPos = currentTag.Length;
  2505. int c = 0;
  2506. while(c != quoteChar)
  2507. {
  2508. c = ReadChar ();
  2509. if(c < 0) throw new XmlException (this as IXmlLineInfo,"Unexpected end of stream in ExternalID.");
  2510. if(c != quoteChar && !XmlChar.IsPubidChar (c))
  2511. throw new XmlException (this as IXmlLineInfo,"character '" + (char)c + "' not allowed for PUBLIC ID");
  2512. }
  2513. return currentTag.ToString (startPos, currentTag.Length - 1 - startPos);
  2514. }
  2515. // The reader is positioned on the first character
  2516. // of the name.
  2517. internal string ReadName ()
  2518. {
  2519. return ReadNameOrNmToken(false);
  2520. }
  2521. // The reader is positioned on the first character
  2522. // of the name.
  2523. private string ReadNmToken ()
  2524. {
  2525. return ReadNameOrNmToken(true);
  2526. }
  2527. private string ReadNameOrNmToken(bool isNameToken)
  2528. {
  2529. int ch = PeekChar ();
  2530. if(isNameToken) {
  2531. if (!XmlChar.IsNameChar ((char) ch))
  2532. throw new XmlException (this as IXmlLineInfo,String.Format ("a nmtoken did not start with a legal character {0} ({1})", ch, (char)ch));
  2533. }
  2534. else {
  2535. if (!XmlChar.IsFirstNameChar (ch))
  2536. throw new XmlException (this as IXmlLineInfo,String.Format ("a name did not start with a legal character {0} ({1})", ch, (char)ch));
  2537. }
  2538. nameLength = 0;
  2539. AppendNameChar (ReadChar ());
  2540. while (XmlChar.IsNameChar (PeekChar ())) {
  2541. AppendNameChar (ReadChar ());
  2542. }
  2543. return CreateNameString ();
  2544. }
  2545. // Read the next character and compare it against the
  2546. // specified character.
  2547. private void Expect (int expected)
  2548. {
  2549. int ch = ReadChar ();
  2550. if (ch != expected) {
  2551. throw new XmlException (this as IXmlLineInfo,
  2552. String.Format (
  2553. "expected '{0}' ({1:X}) but found '{2}' ({3:X})",
  2554. (char)expected,
  2555. expected,
  2556. (char)ch,
  2557. ch));
  2558. }
  2559. }
  2560. private void Expect (string expected)
  2561. {
  2562. int len = expected.Length;
  2563. for(int i=0; i< len; i++)
  2564. Expect (expected[i]);
  2565. }
  2566. // Does not consume the first non-whitespace character.
  2567. private bool SkipWhitespace ()
  2568. {
  2569. //FIXME: Should not skip if whitespaceHandling == WhiteSpaceHandling.None
  2570. bool skipped = XmlChar.IsWhitespace (PeekChar ());
  2571. while (XmlChar.IsWhitespace (PeekChar ()))
  2572. ReadChar ();
  2573. return skipped;
  2574. }
  2575. private void ReadWhitespace ()
  2576. {
  2577. if (currentState == XmlNodeType.None)
  2578. currentState = XmlNodeType.XmlDeclaration;
  2579. ClearValueBuffer ();
  2580. int ch = PeekChar ();
  2581. do {
  2582. AppendValueChar (ReadChar ());
  2583. } while ((ch = PeekChar ()) != -1 && XmlChar.IsWhitespace (ch));
  2584. if (currentState == XmlNodeType.Element && ch != -1 && ch != '<')
  2585. ReadText (false);
  2586. else
  2587. SetProperties (XmlNodeType.Whitespace,
  2588. String.Empty,
  2589. false,
  2590. valueBuffer,
  2591. true);
  2592. return; // (PeekChar () != -1);
  2593. }
  2594. // read entity reference from attribute string and if parsable then return the value.
  2595. private string ReadAttributeValueReference ()
  2596. {
  2597. int endEntityPosition = attributeString.IndexOf(';',
  2598. attributeValuePos);
  2599. if (endEntityPosition < 0)
  2600. throw new XmlException ("Insufficient markup of entity reference");
  2601. string entityName = attributeString.Substring (attributeValuePos + 1,
  2602. endEntityPosition - attributeValuePos - 1);
  2603. attributeValuePos = endEntityPosition + 1;
  2604. if(entityName [0] == '#') {
  2605. char c;
  2606. // character entity
  2607. if(entityName [1] == 'x') {
  2608. // hexadecimal
  2609. c = (char) int.Parse ("0" + entityName.Substring (2),
  2610. System.Globalization.NumberStyles.HexNumber);
  2611. } else {
  2612. // decimal
  2613. c = (char) int.Parse (entityName.Substring (1));
  2614. }
  2615. return c.ToString();
  2616. }
  2617. else {
  2618. switch(entityName)
  2619. {
  2620. case "lt": return "<";
  2621. case "gt": return ">";
  2622. case "amp": return "&";
  2623. case "quot": return "\"";
  2624. case "apos": return "'";
  2625. default: return null;
  2626. }
  2627. }
  2628. }
  2629. private string UnescapeAttributeValue (string unresolved)
  2630. {
  2631. if(unresolved == null) return null;
  2632. // trim start/end edge of quotation character.
  2633. return Dereference (unresolved.Substring (1, unresolved.Length - 2), true);
  2634. }
  2635. private string Dereference (string unresolved, bool expandPredefined)
  2636. {
  2637. StringBuilder resolved = new StringBuilder();
  2638. int pos = 0;
  2639. int next = unresolved.IndexOf ('&');
  2640. if(next < 0)
  2641. return unresolved;
  2642. while(next >= 0) {
  2643. if(pos < next)
  2644. resolved.Append (unresolved.Substring (pos, next - pos));// - 1);
  2645. int endPos = unresolved.IndexOf (';', next+1);
  2646. string entityName =
  2647. unresolved.Substring (next + 1, endPos - next - 1);
  2648. if(entityName [0] == '#') {
  2649. char c;
  2650. // character entity
  2651. if(entityName [1] == 'x') {
  2652. // hexadecimal
  2653. c = (char) int.Parse ("0" + entityName.Substring (2),
  2654. System.Globalization.NumberStyles.HexNumber);
  2655. } else {
  2656. // decimal
  2657. c = (char) int.Parse (entityName.Substring (1));
  2658. }
  2659. resolved.Append (c);
  2660. } else {
  2661. char predefined = XmlChar.GetPredefinedEntity (entityName);
  2662. if (expandPredefined && predefined != 0)
  2663. resolved.Append (predefined);
  2664. else
  2665. // With respect to "Value", MS document is helpless
  2666. // and the implemention returns inconsistent value
  2667. // (e.g. XML: "&ent; &amp;ent;" ---> Value: "&ent; &ent;".)
  2668. resolved.Append ("&" + entityName + ";");
  2669. }
  2670. pos = endPos + 1;
  2671. if(pos > unresolved.Length)
  2672. break;
  2673. next = unresolved.IndexOf('&', pos);
  2674. }
  2675. resolved.Append (unresolved.Substring(pos));
  2676. return resolved.ToString();
  2677. }
  2678. #endregion
  2679. }
  2680. }