XmlNode.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821
  1. //
  2. // System.Xml.XmlNode
  3. //
  4. // Author:
  5. // Kral Ferch <[email protected]>
  6. // Atsushi Enomoto <[email protected]>
  7. //
  8. // (C) 2002 Kral Ferch
  9. // (C) 2002 Atsushi Enomoto
  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. using System.Collections;
  33. using System.Globalization;
  34. using System.IO;
  35. using System.Text;
  36. using System.Xml.XPath;
  37. namespace System.Xml
  38. {
  39. public abstract class XmlNode : ICloneable, IEnumerable, IXPathNavigable
  40. {
  41. #region Fields
  42. XmlDocument ownerDocument;
  43. XmlNode parentNode;
  44. XmlLinkedNode lastLinkedChild;
  45. XmlNodeListChildren childNodes;
  46. bool isReadOnly;
  47. #endregion
  48. #region Constructors
  49. internal XmlNode (XmlDocument ownerDocument)
  50. {
  51. this.ownerDocument = ownerDocument;
  52. }
  53. #endregion
  54. #region Properties
  55. public virtual XmlAttributeCollection Attributes {
  56. get { return null; }
  57. }
  58. public virtual string BaseURI {
  59. get {
  60. // Isn't it conformant to W3C XML Base Recommendation?
  61. // As far as I tested, there are not...
  62. return (ParentNode != null) ? ParentNode.BaseURI : String.Empty;
  63. }
  64. }
  65. public virtual XmlNodeList ChildNodes {
  66. get {
  67. if (childNodes == null)
  68. childNodes = new XmlNodeListChildren (this);
  69. return childNodes;
  70. }
  71. }
  72. public virtual XmlNode FirstChild {
  73. get {
  74. if (LastChild != null) {
  75. return LastLinkedChild.NextLinkedSibling;
  76. }
  77. else {
  78. return null;
  79. }
  80. }
  81. }
  82. public virtual bool HasChildNodes {
  83. get { return LastChild != null; }
  84. }
  85. public virtual string InnerText {
  86. get {
  87. StringBuilder builder = new StringBuilder ();
  88. AppendChildValues (this, builder);
  89. return builder.ToString ();
  90. }
  91. set { throw new InvalidOperationException ("This node is read only. Cannot be modified."); }
  92. }
  93. private void AppendChildValues (XmlNode parent, StringBuilder builder)
  94. {
  95. XmlNode node = parent.FirstChild;
  96. while (node != null) {
  97. switch (node.NodeType) {
  98. case XmlNodeType.Text:
  99. case XmlNodeType.CDATA:
  100. case XmlNodeType.SignificantWhitespace:
  101. case XmlNodeType.Whitespace:
  102. builder.Append (node.Value);
  103. break;
  104. }
  105. AppendChildValues (node, builder);
  106. node = node.NextSibling;
  107. }
  108. }
  109. public virtual string InnerXml {
  110. get {
  111. StringWriter sw = new StringWriter ();
  112. XmlTextWriter xtw = new XmlTextWriter (sw);
  113. WriteContentTo (xtw);
  114. return sw.GetStringBuilder ().ToString ();
  115. }
  116. set {
  117. throw new InvalidOperationException ("This node is readonly or doesn't have any children.");
  118. }
  119. }
  120. public virtual bool IsReadOnly {
  121. get { return isReadOnly; }
  122. }
  123. [System.Runtime.CompilerServices.IndexerName("Item")]
  124. public virtual XmlElement this [string name] {
  125. get {
  126. for (int i = 0; i < ChildNodes.Count; i++) {
  127. XmlNode node = ChildNodes [i];
  128. if ((node.NodeType == XmlNodeType.Element) &&
  129. (node.Name == name)) {
  130. return (XmlElement) node;
  131. }
  132. }
  133. return null;
  134. }
  135. }
  136. [System.Runtime.CompilerServices.IndexerName("Item")]
  137. public virtual XmlElement this [string localname, string ns] {
  138. get {
  139. for (int i = 0; i < ChildNodes.Count; i++) {
  140. XmlNode node = ChildNodes [i];
  141. if ((node.NodeType == XmlNodeType.Element) &&
  142. (node.LocalName == localname) &&
  143. (node.NamespaceURI == ns)) {
  144. return (XmlElement) node;
  145. }
  146. }
  147. return null;
  148. }
  149. }
  150. public virtual XmlNode LastChild {
  151. get { return LastLinkedChild; }
  152. }
  153. internal virtual XmlLinkedNode LastLinkedChild {
  154. get { return lastLinkedChild; }
  155. set { lastLinkedChild = value; }
  156. }
  157. public abstract string LocalName { get; }
  158. public abstract string Name { get; }
  159. public virtual string NamespaceURI {
  160. get { return String.Empty; }
  161. }
  162. public virtual XmlNode NextSibling {
  163. get { return null; }
  164. }
  165. public abstract XmlNodeType NodeType { get; }
  166. internal virtual XPathNodeType XPathNodeType {
  167. get {
  168. throw new InvalidOperationException ("Can not get XPath node type from " + this.GetType ().ToString ());
  169. }
  170. }
  171. public virtual string OuterXml {
  172. get {
  173. StringWriter sw = new StringWriter ();
  174. XmlTextWriter xtw = new XmlTextWriter (sw);
  175. WriteTo (xtw);
  176. return sw.ToString ();
  177. }
  178. }
  179. public virtual XmlDocument OwnerDocument {
  180. get { return ownerDocument; }
  181. }
  182. public virtual XmlNode ParentNode {
  183. get { return parentNode; }
  184. }
  185. public virtual string Prefix {
  186. get { return String.Empty; }
  187. set {}
  188. }
  189. public virtual XmlNode PreviousSibling {
  190. get { return null; }
  191. }
  192. public virtual string Value {
  193. get { return null; }
  194. set { throw new InvalidOperationException ("This node does not have a value"); }
  195. }
  196. internal virtual string XmlLang {
  197. get {
  198. if(Attributes != null)
  199. for (int i = 0; i < Attributes.Count; i++) {
  200. XmlAttribute attr = Attributes [i];
  201. if(attr.Name == "xml:lang")
  202. return attr.Value;
  203. }
  204. return (ParentNode != null) ? ParentNode.XmlLang : OwnerDocument.XmlLang;
  205. }
  206. }
  207. internal virtual XmlSpace XmlSpace {
  208. get {
  209. if(Attributes != null) {
  210. for (int i = 0; i < Attributes.Count; i++) {
  211. XmlAttribute attr = Attributes [i];
  212. if(attr.Name == "xml:space") {
  213. switch(attr.Value) {
  214. case "preserve": return XmlSpace.Preserve;
  215. case "default": return XmlSpace.Default;
  216. }
  217. break;
  218. }
  219. }
  220. }
  221. return (ParentNode != null) ? ParentNode.XmlSpace : OwnerDocument.XmlSpace;
  222. }
  223. }
  224. #endregion
  225. #region Methods
  226. public virtual XmlNode AppendChild (XmlNode newChild)
  227. {
  228. // I assume that AppendChild(n) equals to InsertAfter(n, this.LastChild) or InsertBefore(n, null)
  229. return InsertBefore (newChild, null);
  230. }
  231. public virtual XmlNode Clone ()
  232. {
  233. // By MS document, it is equivalent to CloneNode(true).
  234. return this.CloneNode (true);
  235. }
  236. public abstract XmlNode CloneNode (bool deep);
  237. public XPathNavigator CreateNavigator ()
  238. {
  239. XmlDocument document = this.NodeType == XmlNodeType.Document ?
  240. this as XmlDocument : this.ownerDocument;
  241. return document.CreateNavigator (this);
  242. }
  243. public IEnumerator GetEnumerator ()
  244. {
  245. return ChildNodes.GetEnumerator ();
  246. }
  247. public virtual string GetNamespaceOfPrefix (string prefix)
  248. {
  249. if (prefix == null)
  250. throw new ArgumentNullException ("prefix");
  251. XmlNode node;
  252. switch (NodeType) {
  253. case XmlNodeType.Attribute:
  254. node = ((XmlAttribute) this).OwnerElement;
  255. if (node == null)
  256. return String.Empty;
  257. break;
  258. case XmlNodeType.Element:
  259. node = this;
  260. break;
  261. default:
  262. node = ParentNode;
  263. break;
  264. }
  265. while (node != null) {
  266. if (node.Prefix == prefix)
  267. return node.NamespaceURI;
  268. if (node.Attributes != null) {
  269. int count = node.Attributes.Count;
  270. for (int i = 0; i < count; i++) {
  271. XmlAttribute attr = node.Attributes [i];
  272. if (prefix == attr.LocalName && attr.Prefix == "xmlns"
  273. || attr.Name == "xmlns" && prefix == String.Empty)
  274. return attr.Value;
  275. }
  276. }
  277. node = node.ParentNode;
  278. }
  279. return String.Empty;
  280. }
  281. public virtual string GetPrefixOfNamespace (string namespaceURI)
  282. {
  283. XmlNode node;
  284. switch (NodeType) {
  285. case XmlNodeType.Attribute:
  286. node = ((XmlAttribute) this).OwnerElement;
  287. break;
  288. case XmlNodeType.Element:
  289. node = this;
  290. break;
  291. default:
  292. node = ParentNode;
  293. break;
  294. }
  295. while (node != null && node.Attributes != null) {
  296. for (int i = 0; i < Attributes.Count; i++) {
  297. XmlAttribute attr = Attributes [i];
  298. if (attr.Prefix == "xmlns" && attr.Value == namespaceURI)
  299. return attr.LocalName;
  300. else if (attr.Name == "xmlns" && attr.Value == namespaceURI)
  301. return String.Empty;
  302. }
  303. node = node.ParentNode;
  304. }
  305. return String.Empty;
  306. }
  307. object ICloneable.Clone ()
  308. {
  309. return Clone ();
  310. }
  311. IEnumerator IEnumerable.GetEnumerator ()
  312. {
  313. return GetEnumerator ();
  314. }
  315. public virtual XmlNode InsertAfter (XmlNode newChild, XmlNode refChild)
  316. {
  317. // InsertAfter(n1, n2) is equivalent to InsertBefore(n1, n2.PreviousSibling).
  318. // I took this way because current implementation
  319. // Calling InsertBefore() in this method is faster than
  320. // the counterpart, since NextSibling is faster than
  321. // PreviousSibling (these children are forward-only list).
  322. XmlNode argNode = null;
  323. if (refChild != null)
  324. argNode = refChild.NextSibling;
  325. else if (ChildNodes.Count > 0)
  326. argNode = FirstChild;
  327. return InsertBefore (newChild, argNode);
  328. }
  329. public virtual XmlNode InsertBefore (XmlNode newChild, XmlNode refChild)
  330. {
  331. return InsertBefore (newChild, refChild, true, true);
  332. }
  333. // check for the node to be one of node ancestors
  334. internal bool IsAncestor (XmlNode newChild)
  335. {
  336. XmlNode currNode = this.ParentNode;
  337. while(currNode != null)
  338. {
  339. if(currNode == newChild)
  340. return true;
  341. currNode = currNode.ParentNode;
  342. }
  343. return false;
  344. }
  345. internal XmlNode InsertBefore (XmlNode newChild, XmlNode refChild, bool checkNodeType, bool raiseEvent)
  346. {
  347. if (checkNodeType)
  348. CheckNodeInsertion (newChild, refChild);
  349. XmlDocument ownerDoc = (NodeType == XmlNodeType.Document) ? (XmlDocument) this : OwnerDocument;
  350. if (raiseEvent)
  351. ownerDoc.onNodeInserting (newChild, this);
  352. if (newChild.ParentNode != null)
  353. newChild.ParentNode.RemoveChild (newChild, checkNodeType);
  354. if (newChild.NodeType == XmlNodeType.DocumentFragment) {
  355. int x = newChild.ChildNodes.Count;
  356. for (int i = 0; i < x; i++) {
  357. XmlNode n = newChild.ChildNodes [0];
  358. this.InsertBefore (n, refChild); // recursively invokes events. (It is compatible with MS implementation.)
  359. }
  360. }
  361. else {
  362. XmlLinkedNode newLinkedChild = (XmlLinkedNode) newChild;
  363. XmlLinkedNode lastLinkedChild = LastLinkedChild;
  364. newLinkedChild.parentNode = this;
  365. if (refChild == null) {
  366. // newChild is the last child:
  367. // * set newChild as NextSibling of the existing lastchild
  368. // * set LastChild = newChild
  369. // * set NextSibling of newChild as FirstChild
  370. if (LastLinkedChild != null) {
  371. XmlLinkedNode formerFirst = (XmlLinkedNode) FirstChild;
  372. LastLinkedChild.NextLinkedSibling = newLinkedChild;
  373. LastLinkedChild = newLinkedChild;
  374. newLinkedChild.NextLinkedSibling = formerFirst;
  375. } else {
  376. LastLinkedChild = newLinkedChild;
  377. LastLinkedChild.NextLinkedSibling = newLinkedChild; // FirstChild
  378. }
  379. } else {
  380. // newChild is not the last child:
  381. // * if newchild is first, then set next of lastchild is newChild.
  382. // otherwise, set next of previous sibling to newChild
  383. // * set next of newChild to refChild
  384. XmlLinkedNode prev = refChild.PreviousSibling as XmlLinkedNode;
  385. if (prev == null)
  386. LastLinkedChild.NextLinkedSibling = newLinkedChild;
  387. else
  388. prev.NextLinkedSibling = newLinkedChild;
  389. newLinkedChild.NextLinkedSibling = refChild as XmlLinkedNode;
  390. }
  391. switch (newChild.NodeType) {
  392. case XmlNodeType.EntityReference:
  393. ((XmlEntityReference) newChild).SetReferencedEntityContent ();
  394. break;
  395. case XmlNodeType.Entity:
  396. ((XmlEntity) newChild).SetEntityContent ();
  397. break;
  398. case XmlNodeType.DocumentType:
  399. foreach (XmlEntity ent in ((XmlDocumentType)newChild).Entities)
  400. ent.SetEntityContent ();
  401. break;
  402. }
  403. if (raiseEvent)
  404. ownerDoc.onNodeInserted (newChild, newChild.ParentNode);
  405. }
  406. return newChild;
  407. }
  408. private void CheckNodeInsertion (XmlNode newChild, XmlNode refChild)
  409. {
  410. XmlDocument ownerDoc = (NodeType == XmlNodeType.Document) ? (XmlDocument) this : OwnerDocument;
  411. if (NodeType != XmlNodeType.Element &&
  412. NodeType != XmlNodeType.Attribute &&
  413. NodeType != XmlNodeType.Document &&
  414. NodeType != XmlNodeType.DocumentFragment)
  415. throw new InvalidOperationException (String.Format ("Node cannot be appended to current node {0}.", NodeType));
  416. switch (NodeType) {
  417. case XmlNodeType.Attribute:
  418. switch (newChild.NodeType) {
  419. case XmlNodeType.Text:
  420. case XmlNodeType.EntityReference:
  421. break;
  422. default:
  423. throw new InvalidOperationException (String.Format (
  424. "Cannot insert specified type of node {0} as a child of this node {1}.",
  425. newChild.NodeType, NodeType));
  426. }
  427. break;
  428. case XmlNodeType.Element:
  429. switch (newChild.NodeType) {
  430. case XmlNodeType.Attribute:
  431. case XmlNodeType.Document:
  432. case XmlNodeType.DocumentType:
  433. case XmlNodeType.Entity:
  434. case XmlNodeType.Notation:
  435. case XmlNodeType.XmlDeclaration:
  436. throw new InvalidOperationException ("Cannot insert specified type of node as a child of this node.");
  437. }
  438. break;
  439. }
  440. if (IsReadOnly)
  441. throw new InvalidOperationException ("The node is readonly.");
  442. if (newChild.OwnerDocument != ownerDoc)
  443. throw new ArgumentException ("Can't append a node created by another document.");
  444. if (refChild != null) {
  445. if (refChild.ParentNode != this)
  446. throw new ArgumentException ("The reference node is not a child of this node.");
  447. }
  448. if(this == ownerDoc && ownerDoc.DocumentElement != null && (newChild is XmlElement) && newChild != ownerDoc.DocumentElement)
  449. throw new XmlException ("multiple document element not allowed.");
  450. // checking validity finished. then appending...
  451. if (newChild == this || IsAncestor (newChild))
  452. throw new ArgumentException("Cannot insert a node or any ancestor of that node as a child of itself.");
  453. }
  454. public virtual void Normalize ()
  455. {
  456. StringBuilder tmpBuilder = new StringBuilder ();
  457. int count = this.ChildNodes.Count;
  458. int start = 0;
  459. for (int i = 0; i < count; i++) {
  460. XmlNode c = ChildNodes [i];
  461. switch (c.NodeType) {
  462. case XmlNodeType.Text:
  463. case XmlNodeType.Whitespace:
  464. case XmlNodeType.SignificantWhitespace:
  465. tmpBuilder.Append (c.Value);
  466. break;
  467. default:
  468. c.Normalize ();
  469. NormalizeRange (start, i, tmpBuilder);
  470. // Continue to normalize from next node.
  471. start = i + 1;
  472. break;
  473. }
  474. }
  475. if (start < count) {
  476. NormalizeRange (start, count, tmpBuilder);
  477. }
  478. }
  479. private void NormalizeRange (int start, int i, StringBuilder tmpBuilder)
  480. {
  481. int keepPos = -1;
  482. // If Texts and Whitespaces are mixed, Text takes precedence to remain.
  483. // i.e. Whitespace should be removed.
  484. for (int j = start; j < i; j++) {
  485. XmlNode keep = ChildNodes [j];
  486. if (keep.NodeType == XmlNodeType.Text) {
  487. keepPos = j;
  488. break;
  489. }
  490. else if (keep.NodeType == XmlNodeType.SignificantWhitespace)
  491. keepPos = j;
  492. // but don't break up to find Text nodes.
  493. }
  494. if (keepPos >= 0) {
  495. for (int del = start; del < keepPos; del++)
  496. RemoveChild (ChildNodes [start]);
  497. int rest = i - keepPos - 1;
  498. for (int del = 0; del < rest; del++) {
  499. RemoveChild (ChildNodes [start + 1]);
  500. }
  501. }
  502. if (keepPos >= 0)
  503. ChildNodes [start].Value = tmpBuilder.ToString ();
  504. // otherwise nothing to be normalized
  505. tmpBuilder.Length = 0;
  506. }
  507. public virtual XmlNode PrependChild (XmlNode newChild)
  508. {
  509. return InsertAfter (newChild, null);
  510. }
  511. public virtual void RemoveAll ()
  512. {
  513. if (Attributes != null)
  514. Attributes.RemoveAll ();
  515. XmlNode next = null;
  516. for (XmlNode node = FirstChild; node != null; node = next) {
  517. next = node.NextSibling;
  518. RemoveChild (node);
  519. }
  520. }
  521. public virtual XmlNode RemoveChild (XmlNode oldChild)
  522. {
  523. return RemoveChild (oldChild, true);
  524. }
  525. private void CheckNodeRemoval ()
  526. {
  527. if (NodeType != XmlNodeType.Attribute &&
  528. NodeType != XmlNodeType.Element &&
  529. NodeType != XmlNodeType.Document &&
  530. NodeType != XmlNodeType.DocumentFragment)
  531. throw new ArgumentException (String.Format ("This {0} node cannot remove its child.", NodeType));
  532. if (IsReadOnly)
  533. throw new ArgumentException (String.Format ("This {0} node is read only.", NodeType));
  534. }
  535. internal XmlNode RemoveChild (XmlNode oldChild, bool checkNodeType)
  536. {
  537. if (oldChild == null)
  538. throw new NullReferenceException ();
  539. XmlDocument ownerDoc = (NodeType == XmlNodeType.Document) ? (XmlDocument)this : OwnerDocument;
  540. if(oldChild.ParentNode != this)
  541. throw new ArgumentException ("The node to be removed is not a child of this node.");
  542. if (checkNodeType)
  543. ownerDoc.onNodeRemoving (oldChild, oldChild.ParentNode);
  544. if (checkNodeType)
  545. CheckNodeRemoval ();
  546. if (Object.ReferenceEquals (LastLinkedChild, LastLinkedChild.NextLinkedSibling) && Object.ReferenceEquals (LastLinkedChild, oldChild))
  547. // If there is only one children, simply clear.
  548. LastLinkedChild = null;
  549. else {
  550. XmlLinkedNode oldLinkedChild = (XmlLinkedNode) oldChild;
  551. XmlLinkedNode beforeLinkedChild = LastLinkedChild;
  552. XmlLinkedNode firstChild = (XmlLinkedNode) FirstChild;
  553. while (Object.ReferenceEquals (beforeLinkedChild.NextLinkedSibling, LastLinkedChild) == false &&
  554. Object.ReferenceEquals (beforeLinkedChild.NextLinkedSibling, oldLinkedChild) == false)
  555. beforeLinkedChild = beforeLinkedChild.NextLinkedSibling;
  556. if (Object.ReferenceEquals (beforeLinkedChild.NextLinkedSibling, oldLinkedChild) == false)
  557. throw new ArgumentException ();
  558. beforeLinkedChild.NextLinkedSibling = oldLinkedChild.NextLinkedSibling;
  559. // Each derived class may have its own LastLinkedChild, so we must set it explicitly.
  560. if (oldLinkedChild.NextLinkedSibling == firstChild)
  561. this.LastLinkedChild = beforeLinkedChild;
  562. oldLinkedChild.NextLinkedSibling = null;
  563. }
  564. if (checkNodeType)
  565. ownerDoc.onNodeRemoved (oldChild, oldChild.ParentNode);
  566. oldChild.parentNode = null; // clear parent 'after' above logic.
  567. return oldChild;
  568. }
  569. public virtual XmlNode ReplaceChild (XmlNode newChild, XmlNode oldChild)
  570. {
  571. if(oldChild.ParentNode != this)
  572. throw new ArgumentException ("The node to be removed is not a child of this node.");
  573. if (newChild == this || IsAncestor (newChild))
  574. throw new InvalidOperationException("Cannot insert a node or any ancestor of that node as a child of itself.");
  575. for (int i = 0; i < ChildNodes.Count; i++) {
  576. XmlNode n = ChildNodes [i];
  577. if(n == oldChild) {
  578. XmlNode prev = oldChild.PreviousSibling;
  579. RemoveChild (oldChild);
  580. InsertAfter (newChild, prev);
  581. break;
  582. }
  583. }
  584. return oldChild;
  585. }
  586. internal void SearchDescendantElements (string name, bool matchAll, ArrayList list)
  587. {
  588. for (int i = 0; i < ChildNodes.Count; i++) {
  589. XmlNode n = ChildNodes [i];
  590. if (n.NodeType != XmlNodeType.Element)
  591. continue;
  592. if (matchAll || n.Name == name)
  593. list.Add (n);
  594. n.SearchDescendantElements (name, matchAll, list);
  595. }
  596. }
  597. internal void SearchDescendantElements (string name, bool matchAllName, string ns, bool matchAllNS, ArrayList list)
  598. {
  599. for (int i = 0; i < ChildNodes.Count; i++) {
  600. XmlNode n = ChildNodes [i];
  601. if (n.NodeType != XmlNodeType.Element)
  602. continue;
  603. if ((matchAllName || n.LocalName == name)
  604. && (matchAllNS || n.NamespaceURI == ns))
  605. list.Add (n);
  606. n.SearchDescendantElements (name, matchAllName, ns, matchAllNS, list);
  607. }
  608. }
  609. public XmlNodeList SelectNodes (string xpath)
  610. {
  611. return SelectNodes (xpath, null);
  612. }
  613. public XmlNodeList SelectNodes (string xpath, XmlNamespaceManager nsmgr)
  614. {
  615. XPathNavigator nav = CreateNavigator ();
  616. XPathExpression expr = nav.Compile (xpath);
  617. if (nsmgr != null)
  618. expr.SetContext (nsmgr);
  619. XPathNodeIterator iter = nav.Select (expr);
  620. ArrayList rgNodes = new ArrayList ();
  621. while (iter.MoveNext ())
  622. {
  623. rgNodes.Add (((XmlDocumentNavigator) iter.Current).Node);
  624. }
  625. return new XmlNodeArrayList (rgNodes);
  626. }
  627. public XmlNode SelectSingleNode (string xpath)
  628. {
  629. return SelectSingleNode (xpath, null);
  630. }
  631. public XmlNode SelectSingleNode (string xpath, XmlNamespaceManager nsmgr)
  632. {
  633. XPathNavigator nav = CreateNavigator ();
  634. XPathExpression expr = nav.Compile (xpath);
  635. if (nsmgr != null)
  636. expr.SetContext (nsmgr);
  637. XPathNodeIterator iter = nav.Select (expr);
  638. if (!iter.MoveNext ())
  639. return null;
  640. return ((XmlDocumentNavigator) iter.Current).Node;
  641. }
  642. internal static void SetReadOnly (XmlNode n)
  643. {
  644. if (n.Attributes != null)
  645. for (int i = 0; i < n.Attributes.Count; i++)
  646. SetReadOnly (n.Attributes [i]);
  647. for (int i = 0; i < n.ChildNodes.Count; i++)
  648. SetReadOnly (n.ChildNodes [i]);
  649. n.isReadOnly = true;
  650. }
  651. internal void SetReadOnly ()
  652. {
  653. isReadOnly = true;
  654. }
  655. public virtual bool Supports (string feature, string version)
  656. {
  657. if (String.Compare (feature, "xml", true, CultureInfo.InvariantCulture) == 0 // not case-sensitive
  658. && (String.Compare (version, "1.0", true, CultureInfo.InvariantCulture) == 0
  659. || String.Compare (version, "2.0", true, CultureInfo.InvariantCulture) == 0))
  660. return true;
  661. else
  662. return false;
  663. }
  664. public abstract void WriteContentTo (XmlWriter w);
  665. public abstract void WriteTo (XmlWriter w);
  666. // It parses this and all the ancestor elements,
  667. // find 'xmlns' declarations, stores and then return them.
  668. internal XmlNamespaceManager ConstructNamespaceManager ()
  669. {
  670. XmlDocument doc = this is XmlDocument ? (XmlDocument)this : this.OwnerDocument;
  671. XmlNamespaceManager nsmgr = new XmlNamespaceManager (doc.NameTable);
  672. XmlElement el = null;
  673. switch(this.NodeType) {
  674. case XmlNodeType.Attribute:
  675. el = ((XmlAttribute)this).OwnerElement;
  676. break;
  677. case XmlNodeType.Element:
  678. el = this as XmlElement;
  679. break;
  680. default:
  681. el = this.ParentNode as XmlElement;
  682. break;
  683. }
  684. while (el != null) {
  685. for (int i = 0; i < el.Attributes.Count; i++) {
  686. XmlAttribute attr = el.Attributes [i];
  687. if(attr.Prefix == "xmlns") {
  688. if (nsmgr.LookupNamespace (attr.LocalName) != attr.Value)
  689. nsmgr.AddNamespace (attr.LocalName, attr.Value);
  690. } else if(attr.Name == "xmlns") {
  691. if(nsmgr.LookupNamespace (String.Empty) != attr.Value)
  692. nsmgr.AddNamespace (String.Empty, attr.Value);
  693. }
  694. }
  695. // When reached to document, then it will set null value :)
  696. el = el.ParentNode as XmlElement;
  697. }
  698. return nsmgr;
  699. }
  700. #endregion
  701. }
  702. }