XPathNavigator.cs 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307
  1. //
  2. // System.Xml.XPath.XPathNavigator
  3. //
  4. // Author:
  5. // Jason Diamond ([email protected])
  6. // Atsushi Enomoto ([email protected])
  7. //
  8. // (C) 2002 Jason Diamond http://injektilo.org/
  9. // (C) 2004 Novell Inc.
  10. //
  11. //
  12. // Permission is hereby granted, free of charge, to any person obtaining
  13. // a copy of this software and associated documentation files (the
  14. // "Software"), to deal in the Software without restriction, including
  15. // without limitation the rights to use, copy, modify, merge, publish,
  16. // distribute, sublicense, and/or sell copies of the Software, and to
  17. // permit persons to whom the Software is furnished to do so, subject to
  18. // the following conditions:
  19. //
  20. // The above copyright notice and this permission notice shall be
  21. // included in all copies or substantial portions of the Software.
  22. //
  23. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  24. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  25. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  26. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  27. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  28. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  29. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  30. //
  31. using System;
  32. #if NET_2_0
  33. using System.Collections;
  34. using System.Collections.Generic;
  35. using System.Diagnostics;
  36. using System.Text;
  37. #endif
  38. using System.IO;
  39. using System.Xml;
  40. using System.Xml.Schema;
  41. using Mono.Xml.XPath;
  42. #if NET_2_0
  43. using NSResolver = System.Xml.IXmlNamespaceResolver;
  44. #else
  45. using NSResolver = System.Xml.XmlNamespaceManager;
  46. #endif
  47. namespace System.Xml.XPath
  48. {
  49. #if NET_2_0
  50. public abstract class XPathNavigator : XPathItem,
  51. ICloneable, IXPathNavigable, IXmlNamespaceResolver
  52. #else
  53. public abstract class XPathNavigator : ICloneable
  54. #endif
  55. {
  56. #region Static members
  57. #if NET_2_0
  58. public static IEqualityComparer NavigatorComparer {
  59. get { return XPathNavigatorComparer.Instance; }
  60. }
  61. #endif
  62. #endregion
  63. #region Constructor
  64. protected XPathNavigator ()
  65. {
  66. }
  67. #endregion
  68. #region Properties
  69. public abstract string BaseURI { get; }
  70. #if NET_2_0
  71. public virtual bool CanEdit {
  72. get { return false; }
  73. }
  74. public virtual bool HasAttributes {
  75. get {
  76. if (!MoveToFirstAttribute ())
  77. return false;
  78. MoveToParent ();
  79. return true;
  80. }
  81. }
  82. public virtual bool HasChildren {
  83. get {
  84. if (!MoveToFirstChild ())
  85. return false;
  86. MoveToParent ();
  87. return true;
  88. }
  89. }
  90. #else
  91. public abstract bool HasAttributes { get; }
  92. public abstract bool HasChildren { get; }
  93. #endif
  94. public abstract bool IsEmptyElement { get; }
  95. public abstract string LocalName { get; }
  96. public abstract string Name { get; }
  97. public abstract string NamespaceURI { get; }
  98. public abstract XmlNameTable NameTable { get; }
  99. public abstract XPathNodeType NodeType { get; }
  100. public abstract string Prefix { get; }
  101. #if NET_2_0
  102. public virtual string XmlLang {
  103. get {
  104. XPathNavigator nav = Clone ();
  105. switch (nav.NodeType) {
  106. case XPathNodeType.Attribute:
  107. case XPathNodeType.Namespace:
  108. nav.MoveToParent ();
  109. break;
  110. }
  111. do {
  112. if (nav.MoveToAttribute ("lang", "http://www.w3.org/XML/1998/namespace"))
  113. return nav.Value;
  114. } while (nav.MoveToParent ());
  115. return String.Empty;
  116. }
  117. }
  118. #else
  119. public abstract string Value { get; }
  120. public abstract string XmlLang { get; }
  121. #endif
  122. #endregion
  123. #region Methods
  124. public abstract XPathNavigator Clone ();
  125. public virtual XmlNodeOrder ComparePosition (XPathNavigator nav)
  126. {
  127. if (IsSamePosition (nav))
  128. return XmlNodeOrder.Same;
  129. // quick check for direct descendant
  130. if (IsDescendant (nav))
  131. return XmlNodeOrder.Before;
  132. // quick check for direct ancestor
  133. if (nav.IsDescendant (this))
  134. return XmlNodeOrder.After;
  135. XPathNavigator nav1 = Clone ();
  136. XPathNavigator nav2 = nav.Clone ();
  137. // check if document instance is the same.
  138. nav1.MoveToRoot ();
  139. nav2.MoveToRoot ();
  140. if (!nav1.IsSamePosition (nav2))
  141. return XmlNodeOrder.Unknown;
  142. nav1.MoveTo (this);
  143. nav2.MoveTo (nav);
  144. int depth1 = 0;
  145. while (nav1.MoveToParent ())
  146. depth1++;
  147. nav1.MoveTo (this);
  148. int depth2 = 0;
  149. while (nav2.MoveToParent ())
  150. depth2++;
  151. nav2.MoveTo (nav);
  152. // find common parent depth
  153. int common = depth1;
  154. for (;common > depth2; common--)
  155. nav1.MoveToParent ();
  156. for (int i = depth2; i > common; i--)
  157. nav2.MoveToParent ();
  158. while (!nav1.IsSamePosition (nav2)) {
  159. nav1.MoveToParent ();
  160. nav2.MoveToParent ();
  161. common--;
  162. }
  163. // For each this and target, move to the node that is
  164. // ancestor of the node and child of the common parent.
  165. nav1.MoveTo (this);
  166. for (int i = depth1; i > common + 1; i--)
  167. nav1.MoveToParent ();
  168. nav2.MoveTo (nav);
  169. for (int i = depth2; i > common + 1; i--)
  170. nav2.MoveToParent ();
  171. // Those children of common parent are comparable.
  172. // namespace nodes precede to attributes, and they
  173. // precede to other nodes.
  174. if (nav1.NodeType == XPathNodeType.Namespace) {
  175. if (nav2.NodeType != XPathNodeType.Namespace)
  176. return XmlNodeOrder.Before;
  177. while (nav1.MoveToNextNamespace ())
  178. if (nav1.IsSamePosition (nav2))
  179. return XmlNodeOrder.Before;
  180. return XmlNodeOrder.After;
  181. }
  182. if (nav2.NodeType == XPathNodeType.Namespace)
  183. return XmlNodeOrder.After;
  184. if (nav1.NodeType == XPathNodeType.Attribute) {
  185. if (nav2.NodeType != XPathNodeType.Attribute)
  186. return XmlNodeOrder.Before;
  187. while (nav1.MoveToNextAttribute ())
  188. if (nav1.IsSamePosition (nav2))
  189. return XmlNodeOrder.Before;
  190. return XmlNodeOrder.After;
  191. }
  192. while (nav1.MoveToNext ())
  193. if (nav1.IsSamePosition (nav2))
  194. return XmlNodeOrder.Before;
  195. return XmlNodeOrder.After;
  196. }
  197. public virtual XPathExpression Compile (string xpath)
  198. {
  199. return XPathExpression.Compile (xpath);
  200. }
  201. internal virtual XPathExpression Compile (string xpath, System.Xml.Xsl.IStaticXsltContext ctx)
  202. {
  203. return XPathExpression.Compile (xpath, null, ctx);
  204. }
  205. public virtual object Evaluate (string xpath)
  206. {
  207. return Evaluate (Compile (xpath));
  208. }
  209. public virtual object Evaluate (XPathExpression expr)
  210. {
  211. return Evaluate (expr, null);
  212. }
  213. public virtual object Evaluate (XPathExpression expr, XPathNodeIterator context)
  214. {
  215. return Evaluate (expr, context, null);
  216. }
  217. internal virtual object Evaluate (XPathExpression expr, XPathNodeIterator context, NSResolver ctx)
  218. {
  219. CompiledExpression cexpr = (CompiledExpression) expr;
  220. if (ctx == null)
  221. ctx = cexpr.NamespaceManager;
  222. if (context == null)
  223. context = new NullIterator (this, ctx);
  224. BaseIterator iterContext = (BaseIterator) context;
  225. iterContext.NamespaceManager = ctx;
  226. return cexpr.Evaluate (iterContext);
  227. }
  228. internal XPathNodeIterator EvaluateNodeSet (XPathExpression expr, XPathNodeIterator context, NSResolver ctx)
  229. {
  230. CompiledExpression cexpr = (CompiledExpression) expr;
  231. if (ctx == null)
  232. ctx = cexpr.NamespaceManager;
  233. if (context == null)
  234. context = new NullIterator (this, cexpr.NamespaceManager);
  235. BaseIterator iterContext = (BaseIterator) context;
  236. iterContext.NamespaceManager = ctx;
  237. return cexpr.EvaluateNodeSet (iterContext);
  238. }
  239. internal string EvaluateString (XPathExpression expr, XPathNodeIterator context, NSResolver ctx)
  240. {
  241. CompiledExpression cexpr = (CompiledExpression) expr;
  242. if (ctx == null)
  243. ctx = cexpr.NamespaceManager;
  244. if (context == null)
  245. context = new NullIterator (this, cexpr.NamespaceManager);
  246. BaseIterator iterContext = (BaseIterator) context;
  247. iterContext.NamespaceManager = ctx;
  248. return cexpr.EvaluateString (iterContext);
  249. }
  250. internal double EvaluateNumber (XPathExpression expr, XPathNodeIterator context, NSResolver ctx)
  251. {
  252. CompiledExpression cexpr = (CompiledExpression) expr;
  253. if (ctx == null)
  254. ctx = cexpr.NamespaceManager;
  255. if (context == null)
  256. context = new NullIterator (this, cexpr.NamespaceManager);
  257. BaseIterator iterContext = (BaseIterator) context;
  258. iterContext.NamespaceManager = ctx;
  259. return cexpr.EvaluateNumber (iterContext);
  260. }
  261. internal bool EvaluateBoolean (XPathExpression expr, XPathNodeIterator context, NSResolver ctx)
  262. {
  263. CompiledExpression cexpr = (CompiledExpression) expr;
  264. if (ctx == null)
  265. ctx = cexpr.NamespaceManager;
  266. if (context == null)
  267. context = new NullIterator (this, cexpr.NamespaceManager);
  268. BaseIterator iterContext = (BaseIterator) context;
  269. iterContext.NamespaceManager = ctx;
  270. return cexpr.EvaluateBoolean (iterContext);
  271. }
  272. #if NET_2_0
  273. public virtual string GetAttribute (string localName, string namespaceURI)
  274. {
  275. if (!MoveToAttribute (localName, namespaceURI))
  276. return String.Empty;
  277. string value = Value;
  278. MoveToParent ();
  279. return value;
  280. }
  281. public virtual string GetNamespace (string name)
  282. {
  283. if (!MoveToNamespace (name))
  284. return String.Empty;
  285. string value = Value;
  286. MoveToParent ();
  287. return value;
  288. }
  289. #else
  290. public abstract string GetAttribute (string localName, string namespaceURI);
  291. public abstract string GetNamespace (string name);
  292. #endif
  293. object ICloneable.Clone ()
  294. {
  295. return Clone ();
  296. }
  297. public virtual bool IsDescendant (XPathNavigator nav)
  298. {
  299. if (nav != null)
  300. {
  301. nav = nav.Clone ();
  302. while (nav.MoveToParent ())
  303. {
  304. if (IsSamePosition (nav))
  305. return true;
  306. }
  307. }
  308. return false;
  309. }
  310. public abstract bool IsSamePosition (XPathNavigator other);
  311. public virtual bool Matches (string xpath)
  312. {
  313. return Matches (Compile (xpath));
  314. }
  315. public virtual bool Matches (XPathExpression expr)
  316. {
  317. Expression e = ((CompiledExpression) expr).ExpressionNode;
  318. if (e is ExprRoot)
  319. return NodeType == XPathNodeType.Root;
  320. NodeTest nt = e as NodeTest;
  321. if (nt != null) {
  322. switch (nt.Axis.Axis) {
  323. case Axes.Child:
  324. case Axes.Attribute:
  325. break;
  326. default:
  327. throw new XPathException ("Only child and attribute pattern are allowed for a pattern.");
  328. }
  329. return nt.Match (((CompiledExpression)expr).NamespaceManager, this);
  330. }
  331. if (e is ExprFilter) {
  332. do {
  333. e = ((ExprFilter) e).LeftHandSide;
  334. } while (e is ExprFilter);
  335. if (e is NodeTest && !((NodeTest) e).Match (((CompiledExpression) expr).NamespaceManager, this))
  336. return false;
  337. }
  338. XPathResultType resultType = e.ReturnType;
  339. switch (resultType) {
  340. case XPathResultType.Any:
  341. case XPathResultType.NodeSet:
  342. break;
  343. default:
  344. return false;
  345. }
  346. switch (e.EvaluatedNodeType) {
  347. case XPathNodeType.Attribute:
  348. case XPathNodeType.Namespace:
  349. if (NodeType != e.EvaluatedNodeType)
  350. return false;
  351. break;
  352. }
  353. XPathNodeIterator nodes;
  354. nodes = this.Select (expr);
  355. while (nodes.MoveNext ()) {
  356. if (IsSamePosition (nodes.Current))
  357. return true;
  358. }
  359. // ancestors might select this node.
  360. XPathNavigator navigator = Clone ();
  361. while (navigator.MoveToParent ()) {
  362. nodes = navigator.Select (expr);
  363. while (nodes.MoveNext ()) {
  364. if (IsSamePosition (nodes.Current))
  365. return true;
  366. }
  367. }
  368. return false;
  369. }
  370. public abstract bool MoveTo (XPathNavigator other);
  371. #if NET_2_0
  372. public virtual bool MoveToAttribute (string localName, string namespaceURI)
  373. {
  374. if (MoveToFirstAttribute ()) {
  375. do {
  376. if (LocalName == localName && NamespaceURI == namespaceURI)
  377. return true;
  378. } while (MoveToNextAttribute ());
  379. MoveToParent ();
  380. }
  381. return false;
  382. }
  383. public virtual bool MoveToNamespace (string name)
  384. {
  385. if (MoveToFirstNamespace ()) {
  386. do {
  387. if (LocalName == name)
  388. return true;
  389. } while (MoveToNextNamespace ());
  390. MoveToParent ();
  391. }
  392. return false;
  393. }
  394. /*
  395. public virtual bool MoveToFirst ()
  396. {
  397. if (MoveToPrevious ()) {
  398. // It would be able to invoke MoveToPrevious() until the end, but this way would be much faster
  399. MoveToParent ();
  400. MoveToFirstChild ();
  401. return true;
  402. }
  403. return false;
  404. }
  405. */
  406. public virtual bool MoveToFirst ()
  407. {
  408. return MoveToFirstImpl ();
  409. }
  410. public virtual void MoveToRoot ()
  411. {
  412. while (MoveToParent ())
  413. ;
  414. }
  415. #else
  416. public abstract bool MoveToAttribute (string localName, string namespaceURI);
  417. public abstract bool MoveToNamespace (string name);
  418. public abstract bool MoveToFirst ();
  419. public abstract void MoveToRoot ();
  420. #endif
  421. internal bool MoveToFirstImpl ()
  422. {
  423. switch (NodeType) {
  424. case XPathNodeType.Attribute:
  425. case XPathNodeType.Namespace:
  426. return false;
  427. default:
  428. if (!MoveToParent ())
  429. return false;
  430. // Follow these 2 steps so that we can skip
  431. // some types of nodes .
  432. MoveToFirstChild ();
  433. return true;
  434. }
  435. }
  436. public abstract bool MoveToFirstAttribute ();
  437. public abstract bool MoveToFirstChild ();
  438. public bool MoveToFirstNamespace ()
  439. {
  440. return MoveToFirstNamespace (XPathNamespaceScope.All);
  441. }
  442. public abstract bool MoveToFirstNamespace (XPathNamespaceScope namespaceScope);
  443. public abstract bool MoveToId (string id);
  444. public abstract bool MoveToNext ();
  445. public abstract bool MoveToNextAttribute ();
  446. public bool MoveToNextNamespace ()
  447. {
  448. return MoveToNextNamespace (XPathNamespaceScope.All);
  449. }
  450. public abstract bool MoveToNextNamespace (XPathNamespaceScope namespaceScope);
  451. public abstract bool MoveToParent ();
  452. public abstract bool MoveToPrevious ();
  453. public virtual XPathNodeIterator Select (string xpath)
  454. {
  455. return Select (Compile (xpath));
  456. }
  457. public virtual XPathNodeIterator Select (XPathExpression expr)
  458. {
  459. return Select (expr, null);
  460. }
  461. internal virtual XPathNodeIterator Select (XPathExpression expr, NSResolver ctx)
  462. {
  463. CompiledExpression cexpr = (CompiledExpression) expr;
  464. if (ctx == null)
  465. ctx = cexpr.NamespaceManager;
  466. BaseIterator iter = new NullIterator (this, ctx);
  467. return cexpr.EvaluateNodeSet (iter);
  468. }
  469. public virtual XPathNodeIterator SelectAncestors (XPathNodeType type, bool matchSelf)
  470. {
  471. Axes axis = (matchSelf) ? Axes.AncestorOrSelf : Axes.Ancestor;
  472. return SelectTest (new NodeTypeTest (axis, type));
  473. }
  474. public virtual XPathNodeIterator SelectAncestors (string name, string namespaceURI, bool matchSelf)
  475. {
  476. if (name == null)
  477. throw new ArgumentNullException ("name");
  478. if (namespaceURI == null)
  479. throw new ArgumentNullException ("namespaceURI");
  480. Axes axis = (matchSelf) ? Axes.AncestorOrSelf : Axes.Ancestor;
  481. XmlQualifiedName qname = new XmlQualifiedName (name, namespaceURI);
  482. return SelectTest (new NodeNameTest (axis, qname, true));
  483. }
  484. public virtual XPathNodeIterator SelectChildren (XPathNodeType type)
  485. {
  486. return SelectTest (new NodeTypeTest (Axes.Child, type));
  487. }
  488. public virtual XPathNodeIterator SelectChildren (string name, string namespaceURI)
  489. {
  490. if (name == null)
  491. throw new ArgumentNullException ("name");
  492. if (namespaceURI == null)
  493. throw new ArgumentNullException ("namespaceURI");
  494. Axes axis = Axes.Child;
  495. XmlQualifiedName qname = new XmlQualifiedName (name, namespaceURI);
  496. return SelectTest (new NodeNameTest (axis, qname, true));
  497. }
  498. public virtual XPathNodeIterator SelectDescendants (XPathNodeType type, bool matchSelf)
  499. {
  500. Axes axis = (matchSelf) ? Axes.DescendantOrSelf : Axes.Descendant;
  501. return SelectTest (new NodeTypeTest (axis, type));
  502. }
  503. public virtual XPathNodeIterator SelectDescendants (string name, string namespaceURI, bool matchSelf)
  504. {
  505. if (name == null)
  506. throw new ArgumentNullException ("name");
  507. if (namespaceURI == null)
  508. throw new ArgumentNullException ("namespaceURI");
  509. Axes axis = (matchSelf) ? Axes.DescendantOrSelf : Axes.Descendant;
  510. XmlQualifiedName qname = new XmlQualifiedName (name, namespaceURI);
  511. return SelectTest (new NodeNameTest (axis, qname, true));
  512. }
  513. internal XPathNodeIterator SelectTest (NodeTest test)
  514. {
  515. return test.EvaluateNodeSet (new NullIterator (this));
  516. }
  517. public override string ToString ()
  518. {
  519. return Value;
  520. }
  521. #endregion
  522. #if NET_2_0
  523. public virtual bool CheckValidity (XmlSchemaSet schemas, ValidationEventHandler handler)
  524. {
  525. XmlReaderSettings settings = new XmlReaderSettings ();
  526. settings.NameTable = NameTable;
  527. settings.SetSchemas (schemas);
  528. settings.ValidationEventHandler += handler;
  529. settings.ValidationType = ValidationType.Schema;
  530. try {
  531. XmlReader r = XmlReader.Create (
  532. ReadSubtree (), settings);
  533. while (!r.EOF)
  534. r.Read ();
  535. } catch (XmlSchemaValidationException) {
  536. return false;
  537. }
  538. return true;
  539. }
  540. public virtual XPathNavigator CreateNavigator ()
  541. {
  542. return Clone ();
  543. }
  544. public virtual object Evaluate (string xpath, IXmlNamespaceResolver nsResolver)
  545. {
  546. return Evaluate (Compile (xpath), null, nsResolver);
  547. }
  548. public virtual IDictionary<string, string> GetNamespacesInScope (XmlNamespaceScope scope)
  549. {
  550. IDictionary<string, string> table = new Dictionary<string, string> ();
  551. XPathNamespaceScope xpscope =
  552. scope == XmlNamespaceScope.Local ?
  553. XPathNamespaceScope.Local :
  554. scope == XmlNamespaceScope.ExcludeXml ?
  555. XPathNamespaceScope.ExcludeXml :
  556. XPathNamespaceScope.All;
  557. XPathNavigator nav = Clone ();
  558. if (nav.NodeType != XPathNodeType.Element)
  559. nav.MoveToParent ();
  560. if (!nav.MoveToFirstNamespace (xpscope))
  561. return table;
  562. do {
  563. table.Add (nav.Name, nav.Value);
  564. } while (nav.MoveToNextNamespace (xpscope));
  565. return table;
  566. }
  567. public virtual string LookupNamespace (string prefix)
  568. {
  569. XPathNavigator nav = Clone ();
  570. if (nav.NodeType != XPathNodeType.Element)
  571. nav.MoveToParent ();
  572. if (nav.MoveToNamespace (prefix))
  573. return nav.Value;
  574. return null;
  575. }
  576. public virtual string LookupPrefix (string namespaceUri)
  577. {
  578. XPathNavigator nav = Clone ();
  579. if (nav.NodeType != XPathNodeType.Element)
  580. nav.MoveToParent ();
  581. if (!nav.MoveToFirstNamespace ())
  582. return null;
  583. do {
  584. if (nav.Value == namespaceUri)
  585. return nav.Name;
  586. } while (nav.MoveToNextNamespace ());
  587. return null;
  588. }
  589. private bool MoveTo (XPathNodeIterator iter)
  590. {
  591. if (iter.MoveNext ()) {
  592. MoveTo (iter.Current);
  593. return true;
  594. }
  595. else
  596. return false;
  597. }
  598. public virtual bool MoveToChild (XPathNodeType type)
  599. {
  600. return MoveTo (SelectChildren (type));
  601. }
  602. public virtual bool MoveToChild (string localName, string namespaceURI)
  603. {
  604. return MoveTo (SelectChildren (localName, namespaceURI));
  605. }
  606. public virtual bool MoveToNext (string localName, string namespaceURI)
  607. {
  608. XPathNavigator nav = Clone ();
  609. while (nav.MoveToNext ()) {
  610. if (nav.LocalName == localName &&
  611. nav.NamespaceURI == namespaceURI) {
  612. MoveTo (nav);
  613. return true;
  614. }
  615. }
  616. return false;
  617. }
  618. public virtual bool MoveToNext (XPathNodeType type)
  619. {
  620. XPathNavigator nav = Clone ();
  621. while (nav.MoveToNext ()) {
  622. if (nav.NodeType == type) {
  623. MoveTo (nav);
  624. return true;
  625. }
  626. }
  627. return false;
  628. }
  629. public virtual bool MoveToFollowing (string localName,
  630. string namespaceURI)
  631. {
  632. return MoveToFollowing (localName, namespaceURI, null);
  633. }
  634. public virtual bool MoveToFollowing (string localName,
  635. string namespaceURI, XPathNavigator end)
  636. {
  637. if (localName == null)
  638. throw new ArgumentNullException ("localName");
  639. if (namespaceURI == null)
  640. throw new ArgumentNullException ("namespaceURI");
  641. localName = NameTable.Get (localName);
  642. if (localName == null)
  643. return false;
  644. namespaceURI = NameTable.Get (namespaceURI);
  645. if (namespaceURI == null)
  646. return false;
  647. XPathNavigator nav = Clone ();
  648. switch (nav.NodeType) {
  649. case XPathNodeType.Attribute:
  650. case XPathNodeType.Namespace:
  651. nav.MoveToParent ();
  652. break;
  653. }
  654. do {
  655. if (!nav.MoveToFirstChild ()) {
  656. do {
  657. if (!nav.MoveToNext ()) {
  658. if (!nav.MoveToParent ())
  659. return false;
  660. }
  661. else
  662. break;
  663. } while (true);
  664. }
  665. if (end != null && end.IsSamePosition (nav))
  666. return false;
  667. if (object.ReferenceEquals (localName, nav.LocalName) &&
  668. object.ReferenceEquals (namespaceURI, nav.NamespaceURI)) {
  669. MoveTo (nav);
  670. return true;
  671. }
  672. } while (true);
  673. }
  674. public virtual bool MoveToFollowing (XPathNodeType type)
  675. {
  676. return MoveToFollowing (type, null);
  677. }
  678. public virtual bool MoveToFollowing (XPathNodeType type,
  679. XPathNavigator end)
  680. {
  681. if (type == XPathNodeType.Root)
  682. return false; // will never match
  683. XPathNavigator nav = Clone ();
  684. switch (nav.NodeType) {
  685. case XPathNodeType.Attribute:
  686. case XPathNodeType.Namespace:
  687. nav.MoveToParent ();
  688. break;
  689. }
  690. do {
  691. if (!nav.MoveToFirstChild ()) {
  692. do {
  693. if (!nav.MoveToNext ()) {
  694. if (!nav.MoveToParent ())
  695. return false;
  696. }
  697. else
  698. break;
  699. } while (true);
  700. }
  701. if (end != null && end.IsSamePosition (nav))
  702. return false;
  703. if (nav.NodeType == type) {
  704. MoveTo (nav);
  705. return true;
  706. }
  707. } while (true);
  708. }
  709. public virtual XmlReader ReadSubtree ()
  710. {
  711. switch (NodeType) {
  712. case XPathNodeType.Element:
  713. case XPathNodeType.Root:
  714. return new XPathNavigatorReader (this);
  715. default:
  716. throw new InvalidOperationException (String.Format ("NodeType {0} is not supported to read as a subtree of an XPathNavigator.", NodeType));
  717. }
  718. }
  719. public virtual XPathNodeIterator Select (string xpath, IXmlNamespaceResolver nsResolver)
  720. {
  721. return Select (Compile (xpath), nsResolver);
  722. }
  723. public virtual XPathNavigator SelectSingleNode (string xpath)
  724. {
  725. return SelectSingleNode (xpath, null);
  726. }
  727. public virtual XPathNavigator SelectSingleNode (string xpath, IXmlNamespaceResolver nsResolver)
  728. {
  729. XPathExpression expr = Compile (xpath);
  730. expr.SetContext (nsResolver);
  731. return SelectSingleNode (expr);
  732. }
  733. public virtual XPathNavigator SelectSingleNode (XPathExpression expression)
  734. {
  735. XPathNodeIterator iter = Select (expression);
  736. if (iter.MoveNext ())
  737. return iter.Current;
  738. else
  739. return null;
  740. }
  741. // it is not very effective code but should just work
  742. public override object ValueAs (Type type, IXmlNamespaceResolver nsResolver)
  743. {
  744. return new XmlAtomicValue (Value, XmlSchemaSimpleType.XsString).ValueAs (type, nsResolver);
  745. }
  746. public virtual void WriteSubtree (XmlWriter writer)
  747. {
  748. writer.WriteNode (this, false);
  749. }
  750. static readonly char [] escape_text_chars =
  751. new char [] {'&', '<', '>'};
  752. static readonly char [] escape_attr_chars =
  753. new char [] {'"', '&', '<', '>', '\r', '\n'};
  754. static string EscapeString (string value, bool attr)
  755. {
  756. StringBuilder sb = null;
  757. char [] escape = attr ? escape_attr_chars : escape_text_chars;
  758. if (value.IndexOfAny (escape) < 0)
  759. return value;
  760. sb = new StringBuilder (value, value.Length + 10);
  761. if (attr)
  762. sb.Replace ("\"", "&quot;");
  763. sb.Replace ("<", "&lt;");
  764. sb.Replace (">", "&gt;");
  765. if (attr) {
  766. sb.Replace ("\r\n", "&#10;");
  767. sb.Replace ("\r", "&#10;");
  768. sb.Replace ("\n", "&#10;");
  769. }
  770. return sb.ToString ();
  771. }
  772. public virtual string InnerXml {
  773. get {
  774. switch (NodeType) {
  775. case XPathNodeType.Element:
  776. case XPathNodeType.Root:
  777. break;
  778. case XPathNodeType.Attribute:
  779. case XPathNodeType.Namespace:
  780. return EscapeString (Value, true);
  781. case XPathNodeType.Text:
  782. case XPathNodeType.Whitespace:
  783. case XPathNodeType.SignificantWhitespace:
  784. return String.Empty;
  785. case XPathNodeType.ProcessingInstruction:
  786. case XPathNodeType.Comment:
  787. return Value;
  788. }
  789. XmlReader r = ReadSubtree ();
  790. r.Read (); // start
  791. // skip the element itself (or will reach to
  792. // EOF if other than element) unless writing
  793. // doc itself
  794. int depth = r.Depth;
  795. if (NodeType != XPathNodeType.Root)
  796. r.Read ();
  797. StringWriter sw = new StringWriter ();
  798. XmlWriterSettings s = new XmlWriterSettings ();
  799. s.ConformanceLevel = ConformanceLevel.Fragment;
  800. s.OmitXmlDeclaration = true;
  801. XmlWriter xtw = XmlWriter.Create (sw, s);
  802. while (!r.EOF && r.Depth > depth)
  803. xtw.WriteNode (r, false);
  804. return sw.ToString ();
  805. }
  806. set {
  807. DeleteChildren ();
  808. if (NodeType == XPathNodeType.Attribute) {
  809. SetValue (value);
  810. return;
  811. }
  812. AppendChild (value);
  813. }
  814. }
  815. public override sealed bool IsNode {
  816. get { return true; }
  817. }
  818. public virtual string OuterXml {
  819. get {
  820. switch (NodeType) {
  821. case XPathNodeType.Attribute:
  822. return String.Concat (
  823. Prefix,
  824. Prefix.Length > 0 ? ":" : String.Empty,
  825. LocalName,
  826. "=\"",
  827. EscapeString (Value, true),
  828. "\"");
  829. break;
  830. case XPathNodeType.Namespace:
  831. return String.Concat (
  832. "xmlns",
  833. LocalName.Length > 0 ? ":" : String.Empty,
  834. LocalName,
  835. "=\"",
  836. EscapeString (Value, true),
  837. "\"");
  838. break;
  839. case XPathNodeType.Text:
  840. return EscapeString (Value, false);
  841. case XPathNodeType.Whitespace:
  842. case XPathNodeType.SignificantWhitespace:
  843. return Value;
  844. }
  845. XmlWriterSettings s = new XmlWriterSettings ();
  846. s.Indent = true;
  847. s.OmitXmlDeclaration = true;
  848. s.ConformanceLevel = ConformanceLevel.Fragment;
  849. StringBuilder sb = new StringBuilder ();
  850. using (XmlWriter w = XmlWriter.Create (sb, s)) {
  851. WriteSubtree (w);
  852. }
  853. return sb.ToString ();
  854. }
  855. set {
  856. switch (NodeType) {
  857. case XPathNodeType.Root:
  858. case XPathNodeType.Attribute:
  859. case XPathNodeType.Namespace:
  860. throw new XmlException ("Setting OuterXml Root, Attribute and Namespace is not supported.");
  861. }
  862. DeleteSelf ();
  863. AppendChild (value);
  864. MoveToFirstChild ();
  865. }
  866. }
  867. public virtual IXmlSchemaInfo SchemaInfo {
  868. get {
  869. return null;
  870. }
  871. }
  872. public override object TypedValue {
  873. get {
  874. switch (NodeType) {
  875. case XPathNodeType.Element:
  876. case XPathNodeType.Attribute:
  877. if (XmlType == null)
  878. break;
  879. XmlSchemaDatatype dt = XmlType.Datatype;
  880. if (dt == null)
  881. break;
  882. return dt.ParseValue (Value, NameTable, this as IXmlNamespaceResolver);
  883. }
  884. return Value;
  885. }
  886. }
  887. public virtual object UnderlyingObject {
  888. get { return null; }
  889. }
  890. public override bool ValueAsBoolean {
  891. get { return XQueryConvert.StringToBoolean (Value); }
  892. }
  893. public override DateTime ValueAsDateTime {
  894. get { return XmlConvert.ToDateTime (Value); }
  895. }
  896. public override double ValueAsDouble {
  897. get { return XQueryConvert.StringToDouble (Value); }
  898. }
  899. public override int ValueAsInt {
  900. get { return XQueryConvert.StringToInt (Value); }
  901. }
  902. public override long ValueAsLong {
  903. get { return XQueryConvert.StringToInteger (Value); }
  904. }
  905. public override Type ValueType {
  906. get {
  907. return SchemaInfo != null &&
  908. SchemaInfo.SchemaType != null &&
  909. SchemaInfo.SchemaType.Datatype != null ?
  910. SchemaInfo.SchemaType.Datatype.ValueType
  911. : null;
  912. }
  913. }
  914. public override XmlSchemaType XmlType {
  915. get {
  916. if (SchemaInfo != null)
  917. return SchemaInfo.SchemaType;
  918. return null;
  919. }
  920. }
  921. private XmlReader CreateFragmentReader (string fragment)
  922. {
  923. XmlReaderSettings settings = new XmlReaderSettings ();
  924. settings.ConformanceLevel = ConformanceLevel.Fragment;
  925. XmlNamespaceManager nsmgr = new XmlNamespaceManager (NameTable);
  926. foreach (KeyValuePair<string,string> nss in GetNamespacesInScope (XmlNamespaceScope.All))
  927. nsmgr.AddNamespace (nss.Key, nss.Value);
  928. return XmlReader.Create (
  929. new StringReader (fragment),
  930. settings,
  931. new XmlParserContext (NameTable, nsmgr, null, XmlSpace.None));
  932. }
  933. // must override it.
  934. public virtual XmlWriter AppendChild ()
  935. {
  936. throw new NotSupportedException ();
  937. }
  938. public virtual void AppendChild (
  939. string xmlFragments)
  940. {
  941. AppendChild (CreateFragmentReader (xmlFragments));
  942. }
  943. public virtual void AppendChild (
  944. XmlReader reader)
  945. {
  946. XmlWriter w = AppendChild ();
  947. while (!reader.EOF)
  948. w.WriteNode (reader, false);
  949. w.Close ();
  950. }
  951. public virtual void AppendChild (
  952. XPathNavigator nav)
  953. {
  954. AppendChild (new XPathNavigatorReader (nav));
  955. }
  956. public virtual void AppendChildElement (string prefix, string name, string ns, string value)
  957. {
  958. XmlWriter xw = AppendChild ();
  959. xw.WriteStartElement (prefix, name, ns);
  960. xw.WriteString (value);
  961. xw.WriteEndElement ();
  962. xw.Close ();
  963. }
  964. public virtual void CreateAttribute (string prefix, string localName, string namespaceURI, string value)
  965. {
  966. using (XmlWriter w = CreateAttributes ()) {
  967. w.WriteAttributeString (prefix, localName, namespaceURI, value);
  968. }
  969. }
  970. // must override it.
  971. public virtual XmlWriter CreateAttributes ()
  972. {
  973. throw new NotSupportedException ();
  974. }
  975. // must override it.
  976. public virtual void DeleteSelf ()
  977. {
  978. throw new NotSupportedException ();
  979. }
  980. // must override it.
  981. public virtual void DeleteRange (XPathNavigator nav)
  982. {
  983. throw new NotSupportedException ();
  984. }
  985. public virtual XmlWriter ReplaceRange (XPathNavigator nav)
  986. {
  987. throw new NotSupportedException ();
  988. }
  989. public virtual XmlWriter InsertAfter ()
  990. {
  991. switch (NodeType) {
  992. case XPathNodeType.Root:
  993. case XPathNodeType.Attribute:
  994. case XPathNodeType.Namespace:
  995. throw new InvalidOperationException (String.Format ("Insertion after {0} is not allowed.", NodeType));
  996. }
  997. XPathNavigator nav = Clone ();
  998. if (nav.MoveToNext ())
  999. return nav.InsertBefore ();
  1000. else if (nav.MoveToParent ())
  1001. return nav.AppendChild ();
  1002. else
  1003. throw new InvalidOperationException ("Could not move to parent to insert sibling node");
  1004. }
  1005. public virtual void InsertAfter (string xmlFragments)
  1006. {
  1007. InsertAfter (CreateFragmentReader (xmlFragments));
  1008. }
  1009. public virtual void InsertAfter (XmlReader reader)
  1010. {
  1011. using (XmlWriter w = InsertAfter ()) {
  1012. w.WriteNode (reader, false);
  1013. }
  1014. }
  1015. public virtual void InsertAfter (XPathNavigator nav)
  1016. {
  1017. InsertAfter (new XPathNavigatorReader (nav));
  1018. }
  1019. public virtual XmlWriter InsertBefore ()
  1020. {
  1021. throw new NotSupportedException ();
  1022. }
  1023. public virtual void InsertBefore (string xmlFragments)
  1024. {
  1025. InsertBefore (CreateFragmentReader (xmlFragments));
  1026. }
  1027. public virtual void InsertBefore (XmlReader reader)
  1028. {
  1029. using (XmlWriter w = InsertBefore ()) {
  1030. w.WriteNode (reader, false);
  1031. }
  1032. }
  1033. public virtual void InsertBefore (XPathNavigator nav)
  1034. {
  1035. InsertBefore (new XPathNavigatorReader (nav));
  1036. }
  1037. public virtual void InsertElementAfter (string prefix,
  1038. string localName, string namespaceURI, string value)
  1039. {
  1040. using (XmlWriter w = InsertAfter ()) {
  1041. w.WriteElementString (prefix, localName, namespaceURI, value);
  1042. }
  1043. }
  1044. public virtual void InsertElementBefore (string prefix,
  1045. string localName, string namespaceURI, string value)
  1046. {
  1047. using (XmlWriter w = InsertBefore ()) {
  1048. w.WriteElementString (prefix, localName, namespaceURI, value);
  1049. }
  1050. }
  1051. public virtual XmlWriter PrependChild ()
  1052. {
  1053. XPathNavigator nav = Clone ();
  1054. if (nav.MoveToFirstChild ())
  1055. return nav.InsertBefore ();
  1056. else
  1057. return AppendChild ();
  1058. }
  1059. public virtual void PrependChild (string xmlFragments)
  1060. {
  1061. PrependChild (CreateFragmentReader (xmlFragments));
  1062. }
  1063. public virtual void PrependChild (XmlReader reader)
  1064. {
  1065. using (XmlWriter w = PrependChild ()) {
  1066. w.WriteNode (reader, false);
  1067. }
  1068. }
  1069. public virtual void PrependChild (XPathNavigator nav)
  1070. {
  1071. PrependChild (new XPathNavigatorReader (nav));
  1072. }
  1073. public virtual void PrependChildElement (string prefix,
  1074. string localName, string namespaceURI, string value)
  1075. {
  1076. using (XmlWriter w = PrependChild ()) {
  1077. w.WriteElementString (prefix, localName, namespaceURI, value);
  1078. }
  1079. }
  1080. public virtual void ReplaceSelf (string xmlFragment)
  1081. {
  1082. ReplaceSelf (CreateFragmentReader (xmlFragment));
  1083. }
  1084. // must override it.
  1085. public virtual void ReplaceSelf (XmlReader reader)
  1086. {
  1087. throw new NotSupportedException ();
  1088. }
  1089. public virtual void ReplaceSelf (XPathNavigator navigator)
  1090. {
  1091. ReplaceSelf (new XPathNavigatorReader (navigator));
  1092. }
  1093. // Dunno the exact purpose, but maybe internal editor use
  1094. [MonoTODO]
  1095. public virtual void SetTypedValue (object value)
  1096. {
  1097. throw new NotSupportedException ();
  1098. }
  1099. public virtual void SetValue (string value)
  1100. {
  1101. throw new NotSupportedException ();
  1102. }
  1103. private void DeleteChildren ()
  1104. {
  1105. switch (NodeType) {
  1106. case XPathNodeType.Namespace:
  1107. throw new InvalidOperationException ("Removing namespace node content is not supported.");
  1108. case XPathNodeType.Attribute:
  1109. return;
  1110. case XPathNodeType.Text:
  1111. case XPathNodeType.SignificantWhitespace:
  1112. case XPathNodeType.Whitespace:
  1113. case XPathNodeType.ProcessingInstruction:
  1114. case XPathNodeType.Comment:
  1115. DeleteSelf ();
  1116. return;
  1117. }
  1118. if (!HasChildren)
  1119. return;
  1120. XPathNavigator nav = Clone ();
  1121. nav.MoveToFirstChild ();
  1122. while (!nav.IsSamePosition (this))
  1123. nav.DeleteSelf ();
  1124. }
  1125. #endif
  1126. }
  1127. }