XPathNavigator.cs 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360
  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. #endif
  568. #if NET_2_0
  569. public
  570. #else
  571. internal
  572. #endif
  573. virtual string LookupNamespace (string prefix)
  574. {
  575. XPathNavigator nav = Clone ();
  576. if (nav.NodeType != XPathNodeType.Element)
  577. nav.MoveToParent ();
  578. if (nav.MoveToNamespace (prefix))
  579. return nav.Value;
  580. return null;
  581. }
  582. #if NET_2_0
  583. public
  584. #else
  585. internal
  586. #endif
  587. virtual string LookupPrefix (string namespaceUri)
  588. {
  589. XPathNavigator nav = Clone ();
  590. if (nav.NodeType != XPathNodeType.Element)
  591. nav.MoveToParent ();
  592. if (!nav.MoveToFirstNamespace ())
  593. return null;
  594. do {
  595. if (nav.Value == namespaceUri)
  596. return nav.Name;
  597. } while (nav.MoveToNextNamespace ());
  598. return null;
  599. }
  600. private bool MoveTo (XPathNodeIterator iter)
  601. {
  602. if (iter.MoveNext ()) {
  603. MoveTo (iter.Current);
  604. return true;
  605. }
  606. else
  607. return false;
  608. }
  609. #if NET_2_0
  610. public
  611. #else
  612. internal
  613. #endif
  614. virtual bool MoveToChild (XPathNodeType type)
  615. {
  616. return MoveTo (SelectChildren (type));
  617. }
  618. #if NET_2_0
  619. public
  620. #else
  621. internal
  622. #endif
  623. virtual bool MoveToChild (string localName, string namespaceURI)
  624. {
  625. return MoveTo (SelectChildren (localName, namespaceURI));
  626. }
  627. #if NET_2_0
  628. public
  629. #else
  630. internal
  631. #endif
  632. virtual bool MoveToNext (string localName, string namespaceURI)
  633. {
  634. XPathNavigator nav = Clone ();
  635. while (nav.MoveToNext ()) {
  636. if (nav.LocalName == localName &&
  637. nav.NamespaceURI == namespaceURI) {
  638. MoveTo (nav);
  639. return true;
  640. }
  641. }
  642. return false;
  643. }
  644. #if NET_2_0
  645. public
  646. #else
  647. internal
  648. #endif
  649. virtual bool MoveToNext (XPathNodeType type)
  650. {
  651. XPathNavigator nav = Clone ();
  652. while (nav.MoveToNext ()) {
  653. if (type == XPathNodeType.All || nav.NodeType == type) {
  654. MoveTo (nav);
  655. return true;
  656. }
  657. }
  658. return false;
  659. }
  660. #if NET_2_0
  661. public
  662. #else
  663. internal
  664. #endif
  665. virtual bool MoveToFollowing (string localName,
  666. string namespaceURI)
  667. {
  668. return MoveToFollowing (localName, namespaceURI, null);
  669. }
  670. #if NET_2_0
  671. public
  672. #else
  673. internal
  674. #endif
  675. virtual bool MoveToFollowing (string localName,
  676. string namespaceURI, XPathNavigator end)
  677. {
  678. if (localName == null)
  679. throw new ArgumentNullException ("localName");
  680. if (namespaceURI == null)
  681. throw new ArgumentNullException ("namespaceURI");
  682. localName = NameTable.Get (localName);
  683. if (localName == null)
  684. return false;
  685. namespaceURI = NameTable.Get (namespaceURI);
  686. if (namespaceURI == null)
  687. return false;
  688. XPathNavigator nav = Clone ();
  689. switch (nav.NodeType) {
  690. case XPathNodeType.Attribute:
  691. case XPathNodeType.Namespace:
  692. nav.MoveToParent ();
  693. break;
  694. }
  695. do {
  696. if (!nav.MoveToFirstChild ()) {
  697. do {
  698. if (!nav.MoveToNext ()) {
  699. if (!nav.MoveToParent ())
  700. return false;
  701. }
  702. else
  703. break;
  704. } while (true);
  705. }
  706. if (end != null && end.IsSamePosition (nav))
  707. return false;
  708. if (object.ReferenceEquals (localName, nav.LocalName) &&
  709. object.ReferenceEquals (namespaceURI, nav.NamespaceURI)) {
  710. MoveTo (nav);
  711. return true;
  712. }
  713. } while (true);
  714. }
  715. #if NET_2_0
  716. public
  717. #else
  718. internal
  719. #endif
  720. virtual bool MoveToFollowing (XPathNodeType type)
  721. {
  722. return MoveToFollowing (type, null);
  723. }
  724. #if NET_2_0
  725. public
  726. #else
  727. internal
  728. #endif
  729. virtual bool MoveToFollowing (XPathNodeType type,
  730. XPathNavigator end)
  731. {
  732. if (type == XPathNodeType.Root)
  733. return false; // will never match
  734. XPathNavigator nav = Clone ();
  735. switch (nav.NodeType) {
  736. case XPathNodeType.Attribute:
  737. case XPathNodeType.Namespace:
  738. nav.MoveToParent ();
  739. break;
  740. }
  741. do {
  742. if (!nav.MoveToFirstChild ()) {
  743. do {
  744. if (!nav.MoveToNext ()) {
  745. if (!nav.MoveToParent ())
  746. return false;
  747. }
  748. else
  749. break;
  750. } while (true);
  751. }
  752. if (end != null && end.IsSamePosition (nav))
  753. return false;
  754. if (type == XPathNodeType.All || nav.NodeType == type) {
  755. MoveTo (nav);
  756. return true;
  757. }
  758. } while (true);
  759. }
  760. #if NET_2_0
  761. public virtual XmlReader ReadSubtree ()
  762. {
  763. switch (NodeType) {
  764. case XPathNodeType.Element:
  765. case XPathNodeType.Root:
  766. return new XPathNavigatorReader (this);
  767. default:
  768. throw new InvalidOperationException (String.Format ("NodeType {0} is not supported to read as a subtree of an XPathNavigator.", NodeType));
  769. }
  770. }
  771. public virtual XPathNodeIterator Select (string xpath, IXmlNamespaceResolver nsResolver)
  772. {
  773. return Select (Compile (xpath), nsResolver);
  774. }
  775. public virtual XPathNavigator SelectSingleNode (string xpath)
  776. {
  777. return SelectSingleNode (xpath, null);
  778. }
  779. public virtual XPathNavigator SelectSingleNode (string xpath, IXmlNamespaceResolver nsResolver)
  780. {
  781. XPathExpression expr = Compile (xpath);
  782. expr.SetContext (nsResolver);
  783. return SelectSingleNode (expr);
  784. }
  785. public virtual XPathNavigator SelectSingleNode (XPathExpression expression)
  786. {
  787. XPathNodeIterator iter = Select (expression);
  788. if (iter.MoveNext ())
  789. return iter.Current;
  790. else
  791. return null;
  792. }
  793. // it is not very effective code but should just work
  794. public override object ValueAs (Type type, IXmlNamespaceResolver nsResolver)
  795. {
  796. return new XmlAtomicValue (Value, XmlSchemaSimpleType.XsString).ValueAs (type, nsResolver);
  797. }
  798. public virtual void WriteSubtree (XmlWriter writer)
  799. {
  800. writer.WriteNode (this, false);
  801. }
  802. static readonly char [] escape_text_chars =
  803. new char [] {'&', '<', '>'};
  804. static readonly char [] escape_attr_chars =
  805. new char [] {'"', '&', '<', '>', '\r', '\n'};
  806. static string EscapeString (string value, bool attr)
  807. {
  808. StringBuilder sb = null;
  809. char [] escape = attr ? escape_attr_chars : escape_text_chars;
  810. if (value.IndexOfAny (escape) < 0)
  811. return value;
  812. sb = new StringBuilder (value, value.Length + 10);
  813. if (attr)
  814. sb.Replace ("\"", "&quot;");
  815. sb.Replace ("<", "&lt;");
  816. sb.Replace (">", "&gt;");
  817. if (attr) {
  818. sb.Replace ("\r\n", "&#10;");
  819. sb.Replace ("\r", "&#10;");
  820. sb.Replace ("\n", "&#10;");
  821. }
  822. return sb.ToString ();
  823. }
  824. public virtual string InnerXml {
  825. get {
  826. switch (NodeType) {
  827. case XPathNodeType.Element:
  828. case XPathNodeType.Root:
  829. break;
  830. case XPathNodeType.Attribute:
  831. case XPathNodeType.Namespace:
  832. return EscapeString (Value, true);
  833. case XPathNodeType.Text:
  834. case XPathNodeType.Whitespace:
  835. case XPathNodeType.SignificantWhitespace:
  836. return String.Empty;
  837. case XPathNodeType.ProcessingInstruction:
  838. case XPathNodeType.Comment:
  839. return Value;
  840. }
  841. XmlReader r = ReadSubtree ();
  842. r.Read (); // start
  843. // skip the element itself (or will reach to
  844. // EOF if other than element) unless writing
  845. // doc itself
  846. int depth = r.Depth;
  847. if (NodeType != XPathNodeType.Root)
  848. r.Read ();
  849. else
  850. depth = -1; // for Root, it should consume the entire tree, so no depth check is done.
  851. StringWriter sw = new StringWriter ();
  852. XmlWriterSettings s = new XmlWriterSettings ();
  853. s.Indent = true;
  854. s.ConformanceLevel = ConformanceLevel.Fragment;
  855. s.OmitXmlDeclaration = true;
  856. XmlWriter xtw = XmlWriter.Create (sw, s);
  857. while (!r.EOF && r.Depth > depth)
  858. xtw.WriteNode (r, false);
  859. return sw.ToString ();
  860. }
  861. set {
  862. DeleteChildren ();
  863. if (NodeType == XPathNodeType.Attribute) {
  864. SetValue (value);
  865. return;
  866. }
  867. AppendChild (value);
  868. }
  869. }
  870. public override sealed bool IsNode {
  871. get { return true; }
  872. }
  873. public virtual string OuterXml {
  874. get {
  875. switch (NodeType) {
  876. case XPathNodeType.Attribute:
  877. return String.Concat (
  878. Prefix,
  879. Prefix.Length > 0 ? ":" : String.Empty,
  880. LocalName,
  881. "=\"",
  882. EscapeString (Value, true),
  883. "\"");
  884. case XPathNodeType.Namespace:
  885. return String.Concat (
  886. "xmlns",
  887. LocalName.Length > 0 ? ":" : String.Empty,
  888. LocalName,
  889. "=\"",
  890. EscapeString (Value, true),
  891. "\"");
  892. case XPathNodeType.Text:
  893. return EscapeString (Value, false);
  894. case XPathNodeType.Whitespace:
  895. case XPathNodeType.SignificantWhitespace:
  896. return Value;
  897. }
  898. XmlWriterSettings s = new XmlWriterSettings ();
  899. s.Indent = true;
  900. s.OmitXmlDeclaration = true;
  901. s.ConformanceLevel = ConformanceLevel.Fragment;
  902. StringBuilder sb = new StringBuilder ();
  903. using (XmlWriter w = XmlWriter.Create (sb, s)) {
  904. WriteSubtree (w);
  905. }
  906. return sb.ToString ();
  907. }
  908. set {
  909. switch (NodeType) {
  910. case XPathNodeType.Root:
  911. case XPathNodeType.Attribute:
  912. case XPathNodeType.Namespace:
  913. throw new XmlException ("Setting OuterXml Root, Attribute and Namespace is not supported.");
  914. }
  915. DeleteSelf ();
  916. AppendChild (value);
  917. MoveToFirstChild ();
  918. }
  919. }
  920. public virtual IXmlSchemaInfo SchemaInfo {
  921. get {
  922. return null;
  923. }
  924. }
  925. public override object TypedValue {
  926. get {
  927. switch (NodeType) {
  928. case XPathNodeType.Element:
  929. case XPathNodeType.Attribute:
  930. if (XmlType == null)
  931. break;
  932. XmlSchemaDatatype dt = XmlType.Datatype;
  933. if (dt == null)
  934. break;
  935. return dt.ParseValue (Value, NameTable, this as IXmlNamespaceResolver);
  936. }
  937. return Value;
  938. }
  939. }
  940. public virtual object UnderlyingObject {
  941. get { return null; }
  942. }
  943. public override bool ValueAsBoolean {
  944. get { return XQueryConvert.StringToBoolean (Value); }
  945. }
  946. public override DateTime ValueAsDateTime {
  947. get { return XmlConvert.ToDateTime (Value); }
  948. }
  949. public override double ValueAsDouble {
  950. get { return XQueryConvert.StringToDouble (Value); }
  951. }
  952. public override int ValueAsInt {
  953. get { return XQueryConvert.StringToInt (Value); }
  954. }
  955. public override long ValueAsLong {
  956. get { return XQueryConvert.StringToInteger (Value); }
  957. }
  958. public override Type ValueType {
  959. get {
  960. return SchemaInfo != null &&
  961. SchemaInfo.SchemaType != null &&
  962. SchemaInfo.SchemaType.Datatype != null ?
  963. SchemaInfo.SchemaType.Datatype.ValueType
  964. : null;
  965. }
  966. }
  967. public override XmlSchemaType XmlType {
  968. get {
  969. if (SchemaInfo != null)
  970. return SchemaInfo.SchemaType;
  971. return null;
  972. }
  973. }
  974. private XmlReader CreateFragmentReader (string fragment)
  975. {
  976. XmlReaderSettings settings = new XmlReaderSettings ();
  977. settings.ConformanceLevel = ConformanceLevel.Fragment;
  978. XmlNamespaceManager nsmgr = new XmlNamespaceManager (NameTable);
  979. foreach (KeyValuePair<string,string> nss in GetNamespacesInScope (XmlNamespaceScope.All))
  980. nsmgr.AddNamespace (nss.Key, nss.Value);
  981. return XmlReader.Create (
  982. new StringReader (fragment),
  983. settings,
  984. new XmlParserContext (NameTable, nsmgr, null, XmlSpace.None));
  985. }
  986. // must override it.
  987. public virtual XmlWriter AppendChild ()
  988. {
  989. throw new NotSupportedException ();
  990. }
  991. public virtual void AppendChild (
  992. string xmlFragments)
  993. {
  994. AppendChild (CreateFragmentReader (xmlFragments));
  995. }
  996. public virtual void AppendChild (
  997. XmlReader reader)
  998. {
  999. XmlWriter w = AppendChild ();
  1000. while (!reader.EOF)
  1001. w.WriteNode (reader, false);
  1002. w.Close ();
  1003. }
  1004. public virtual void AppendChild (
  1005. XPathNavigator nav)
  1006. {
  1007. AppendChild (new XPathNavigatorReader (nav));
  1008. }
  1009. public virtual void AppendChildElement (string prefix, string name, string ns, string value)
  1010. {
  1011. XmlWriter xw = AppendChild ();
  1012. xw.WriteStartElement (prefix, name, ns);
  1013. xw.WriteString (value);
  1014. xw.WriteEndElement ();
  1015. xw.Close ();
  1016. }
  1017. public virtual void CreateAttribute (string prefix, string localName, string namespaceURI, string value)
  1018. {
  1019. using (XmlWriter w = CreateAttributes ()) {
  1020. w.WriteAttributeString (prefix, localName, namespaceURI, value);
  1021. }
  1022. }
  1023. // must override it.
  1024. public virtual XmlWriter CreateAttributes ()
  1025. {
  1026. throw new NotSupportedException ();
  1027. }
  1028. // must override it.
  1029. public virtual void DeleteSelf ()
  1030. {
  1031. throw new NotSupportedException ();
  1032. }
  1033. // must override it.
  1034. public virtual void DeleteRange (XPathNavigator nav)
  1035. {
  1036. throw new NotSupportedException ();
  1037. }
  1038. public virtual XmlWriter ReplaceRange (XPathNavigator nav)
  1039. {
  1040. throw new NotSupportedException ();
  1041. }
  1042. public virtual XmlWriter InsertAfter ()
  1043. {
  1044. switch (NodeType) {
  1045. case XPathNodeType.Root:
  1046. case XPathNodeType.Attribute:
  1047. case XPathNodeType.Namespace:
  1048. throw new InvalidOperationException (String.Format ("Insertion after {0} is not allowed.", NodeType));
  1049. }
  1050. XPathNavigator nav = Clone ();
  1051. if (nav.MoveToNext ())
  1052. return nav.InsertBefore ();
  1053. else if (nav.MoveToParent ())
  1054. return nav.AppendChild ();
  1055. else
  1056. throw new InvalidOperationException ("Could not move to parent to insert sibling node");
  1057. }
  1058. public virtual void InsertAfter (string xmlFragments)
  1059. {
  1060. InsertAfter (CreateFragmentReader (xmlFragments));
  1061. }
  1062. public virtual void InsertAfter (XmlReader reader)
  1063. {
  1064. using (XmlWriter w = InsertAfter ()) {
  1065. w.WriteNode (reader, false);
  1066. }
  1067. }
  1068. public virtual void InsertAfter (XPathNavigator nav)
  1069. {
  1070. InsertAfter (new XPathNavigatorReader (nav));
  1071. }
  1072. public virtual XmlWriter InsertBefore ()
  1073. {
  1074. throw new NotSupportedException ();
  1075. }
  1076. public virtual void InsertBefore (string xmlFragments)
  1077. {
  1078. InsertBefore (CreateFragmentReader (xmlFragments));
  1079. }
  1080. public virtual void InsertBefore (XmlReader reader)
  1081. {
  1082. using (XmlWriter w = InsertBefore ()) {
  1083. w.WriteNode (reader, false);
  1084. }
  1085. }
  1086. public virtual void InsertBefore (XPathNavigator nav)
  1087. {
  1088. InsertBefore (new XPathNavigatorReader (nav));
  1089. }
  1090. public virtual void InsertElementAfter (string prefix,
  1091. string localName, string namespaceURI, string value)
  1092. {
  1093. using (XmlWriter w = InsertAfter ()) {
  1094. w.WriteElementString (prefix, localName, namespaceURI, value);
  1095. }
  1096. }
  1097. public virtual void InsertElementBefore (string prefix,
  1098. string localName, string namespaceURI, string value)
  1099. {
  1100. using (XmlWriter w = InsertBefore ()) {
  1101. w.WriteElementString (prefix, localName, namespaceURI, value);
  1102. }
  1103. }
  1104. public virtual XmlWriter PrependChild ()
  1105. {
  1106. XPathNavigator nav = Clone ();
  1107. if (nav.MoveToFirstChild ())
  1108. return nav.InsertBefore ();
  1109. else
  1110. return AppendChild ();
  1111. }
  1112. public virtual void PrependChild (string xmlFragments)
  1113. {
  1114. PrependChild (CreateFragmentReader (xmlFragments));
  1115. }
  1116. public virtual void PrependChild (XmlReader reader)
  1117. {
  1118. using (XmlWriter w = PrependChild ()) {
  1119. w.WriteNode (reader, false);
  1120. }
  1121. }
  1122. public virtual void PrependChild (XPathNavigator nav)
  1123. {
  1124. PrependChild (new XPathNavigatorReader (nav));
  1125. }
  1126. public virtual void PrependChildElement (string prefix,
  1127. string localName, string namespaceURI, string value)
  1128. {
  1129. using (XmlWriter w = PrependChild ()) {
  1130. w.WriteElementString (prefix, localName, namespaceURI, value);
  1131. }
  1132. }
  1133. public virtual void ReplaceSelf (string xmlFragment)
  1134. {
  1135. ReplaceSelf (CreateFragmentReader (xmlFragment));
  1136. }
  1137. // must override it.
  1138. public virtual void ReplaceSelf (XmlReader reader)
  1139. {
  1140. throw new NotSupportedException ();
  1141. }
  1142. public virtual void ReplaceSelf (XPathNavigator navigator)
  1143. {
  1144. ReplaceSelf (new XPathNavigatorReader (navigator));
  1145. }
  1146. // Dunno the exact purpose, but maybe internal editor use
  1147. [MonoTODO]
  1148. public virtual void SetTypedValue (object value)
  1149. {
  1150. throw new NotSupportedException ();
  1151. }
  1152. public virtual void SetValue (string value)
  1153. {
  1154. throw new NotSupportedException ();
  1155. }
  1156. private void DeleteChildren ()
  1157. {
  1158. switch (NodeType) {
  1159. case XPathNodeType.Namespace:
  1160. throw new InvalidOperationException ("Removing namespace node content is not supported.");
  1161. case XPathNodeType.Attribute:
  1162. return;
  1163. case XPathNodeType.Text:
  1164. case XPathNodeType.SignificantWhitespace:
  1165. case XPathNodeType.Whitespace:
  1166. case XPathNodeType.ProcessingInstruction:
  1167. case XPathNodeType.Comment:
  1168. DeleteSelf ();
  1169. return;
  1170. }
  1171. if (!HasChildren)
  1172. return;
  1173. XPathNavigator nav = Clone ();
  1174. nav.MoveToFirstChild ();
  1175. while (!nav.IsSamePosition (this))
  1176. nav.DeleteSelf ();
  1177. }
  1178. #endif
  1179. }
  1180. }